Skip to content
Advertisement

Calling wait() after posting a runnable to UI thread until completion

I’m actually in need of waiting for the ui thread to execute a runnable before my application thread can continue. Is the wait()/notify() way a proper way to do it or is there something better for this? What I’m actually doing looks like this:

public void showVideoView() {
    try {
        final AtomicBoolean done = new AtomicBoolean(false);
        final Runnable task = new Runnable() {
            @Override
            public void run() {
                synchronized(this) {
                    mStartupCurtain.setVisibility(View.GONE);
                    mVideoView.setVisibility(View.VISIBLE);
                    mWebView.loadUrl("about:blank");
                    mWebView.setVisibility(View.GONE);
                    done.set(true);
                    notify();
                }
            }
        };
        mUiHandler.post(task);
        synchronized(task) {
            while(!done.get()) {
                task.wait();
            }
            Log.d(TAG, "showVideoView done!");

        }
    } catch (InterruptedException e) {
        Log.e(TAG, "Thread got interrupted while waiting for posted runnable to finish its task");
    }

}

Also when I do this I have to be sure that the thread is not the one of the UI, which happens when I start calling methods from a listener method coming from an interface like MediaPlayer.OnCompletionListener.

What do you think?

Advertisement

Answer

Looks fine to me.

The “done” variable could be a regular Boolean instead of AtomicBoolean since you definitively get/set it’s value within the lock. I like that you check the value of “done” prior to calling wait – since it is quite possible the task will have been completed before you ever enter the lock in the worker thread. If you had not done that, the wait() call would go indefinitely since the notify() had already happened.

There is one edge case to consider that may or may not be applicable to your design. What happens if the UI thread is attempting to exit (i.e. app exit) when the worker thread is still stuck waiting for the task to complete? Another variation is when the worker thread is waiting on the task to complete, but the UI thread is waiting on the worker thread to exit. The latter could be solved with another Boolean variable by which the UI thread signals the worker thread to exit. These issues may or may not be relevant – depending on how the UI is managing the thread to begin with.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement