0

I am using Handler in an android project to give a callback to to the main/ui thread.

        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        mHandler.post(new Runnable() {
            public void run() {
                freeBeePlaybackEventListener.onError(freeBeeError);
            }
        });

When I am creating the handler object i.e. mHandler , I am checking whether the handler already exists or not. If not, then I am creating the handler i.e. using a singleton pattern. My question is: Is creation of the handler object thread safe ?

Thanks.

user2284140
  • 197
  • 1
  • 4
  • 18

2 Answers2

3

No, this code is not thread safe.

But the problem is not the Handler itself but the creation pattern used. If the code that you reported here is called at the same time by two different thread, it may happen a critical race where two different Objects (in this case Handler) are created. If you are sure that this code is called always by the same thread, you can safely use it.

By the way, this is the same problem of the lazy Singleton creation, and it is usually solved in this way:

if( mHandler == null )
{
    syncronized( this )
    {
        if( mHandler == null )
            mHandler = new Handler(Looper.getMainLooper());
    }
}

Where 'this' is a synchronizing object that may be the class container or anything else.

ARLabs
  • 1,465
  • 1
  • 14
  • 25
0

Handles are Thread Safe.

To handle more complex interactions with a worker thread, you might consider using a Handler in your worker thread, to process messages delivered from the UI thread. (DOC-Worker Threads)

Normally, you create a Handler for a new thread, but you can also create a Handler that's connected to an existing thread. When you connect a Handler to your UI thread, the code that handles messages runs on the UI thread (Android Documetation)

Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53