0

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...

David Doria
  • 9,873
  • 17
  • 85
  • 147

1 Answers1

1

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @SLacks I don't suppose there is an easy way to set a timeout on a CountDownLatch? That is, "wait for the count to happen, but if it doesn't in 5 seconds, proceed anyway"? – David Doria Oct 22 '13 at 11:54
  • Sorry, I was too quick on the trigger: http://stackoverflow.com/questions/15245629/abort-countdownlatch-await-after-time-out . Thanks for the pointer! – David Doria Oct 22 '13 at 12:02