1
votes

I've got a database which stores e.g. the key of an image for a TextureAtlas. Because the database query shouldn't block the main thread, the query is executed on another thread.

Now I want to create a scene2d actor and return that, so it can be shown.

new Thread() {
        @Override
        public void run() {
            String resultOfQuery = ...;
            final Image image = new Image(atlas.findRegion(resultOfQuery));

            Gdx.app.postRunnable(new Runnable() {
                @Override
                public void run() {
                    listener.onImageCreated(image);
                }
            }); 
        }
    }.start();

As you can see I'm creating the Image in the new thread and then pass it to the main thread. But the libGDX wiki states:

You should never perform multi-threaded operations on anything that is graphics or audio related, e.g. use scene2D components from multiple threads.

Do I have to create and assign the actor to the stage on the main thread? Or is it ok, if I create it inside another thread and then add it to the stage on the main thread?

1

1 Answers

0
votes

The only potential issue I see above is calling findRegion on the atlas, which isn't thread safe. But if you know that your thread is not running while the atlas is being used elsewhere it would be ok. If you have multiple queries going on that could all potentially access the atlas, you'd have a problem. Or if you are calling atlas methods in your game loop.

Of course, you could simply use the no-argument Image constructor and pass it a region in the game thread runnable. Then you would have nothing to worry about.