2

I am trying to make use of HandlerThread in android and am ending up with either a situation in which the UI thread is not responding anymore, or a strange IllegalStateException. I want to give you a minimal example of my problem.

I have a class DataManager which instantiates a worker thread on creation:

public class DataManager
{
    private final HandlerThread loaderThread = new HandlerThread( "Worker" );
    private final Producer loader;

Inside of this class I have my Handler defined:

    private static class Producer extends Handler
    {
        public Producer( Looper looper )
        {
            super( looper );
        }

        @Override
        public void handleMessage( Message msg )
        {
            msg.recycle();
        }
    }

The constructor of my DataManager runs the worker thread and associates the handler with the thread's looper:

    public DataManager()
    {
        loaderThread.start();
        this.loader = new Producer( loaderThread.getLooper() );
    }

Before DataManager is destroyed, it stops the thread and waits for it to finish. Actually I believe this part is not relevant to my problem, because my DataManager instance is definitely alive all the time:

    @Override
    protected void finalize() throws Throwable
    {
        loaderThread.quit();
        loaderThread.join();

        super.finalize();
    }

Finally, I have doSomething method, which simply posts a message to the worker thread:

    public void doSomething()
    {
        Message msg = Message.obtain();
        loader.sendMessage( msg );
    }

Now I'm instantiating the DataManager from inside of a custom view on the UI thread. When the view is about to paint itself using onDraw it calls doSomething on the DataManager. The further behavior depends on whether an AsyncTask is currently running in background or not:

  • If it is running, than the UI thread is becoming unresponsive form this moment on.
  • Otherwise, I get an IllegalStateException, thrown from within a subroutine of Looper.loop of the UI thread, saying:

    IllegalStateException: The specified message queue synchronization barrier token has not been posted or has already been removed.

Google gives absolutely no results for this message. I've been reading documentation and searching for similar problems for a few hours now and still have no idea what I might be doing wrong. Any ideas?

1 Answer 1

6

Got it. Obsiously the situation about recycling messages is this:

If you send it to a handler, the handler/looper will recycle it for you.

So one must not recycle the message within handleMessage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.