Question

I want to do something like this:

public class MyCallable implements Callable<Boolean>, MyObserver
{
    Boolean mSuccess = false;

    @Override
    public Boolean call() throws Exception
    {
        // ... Wait here until myCallback is called ...

        return mSuccess;
    }

    @Override
    public void myCallback()
    {
        if(something) mSuccess = true;
    }
}

so I can use it like:

MyCallable callable = new MyCallable();

FutureTask<Boolean> futureTask = new FutureTask<Boolean>(callable);

ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(futureTask);

Boolean successfull = futureTask.get();

What would this "Wait for the callback to be called" code look like? I guess I could just make a member called "Boolean mCallbackCalled = false" and just while(!mCallbackCalled), but that seems pretty hacky...

Was it helpful?

Solution

You shouldn't be using executors at all.

Instead, create a CountDownLatch with a count of 1, countDown() it in the callback, then await() it in your calling code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top