DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Use A FutureTask To Block Processing While Waiting For An Asynchronous Call To Return

  • submit to reddit
        // #project-specific
// since implementing push is not an option
// in our controller, we start an async TaskInstance
// We need to wait untill the TaskInstance#getStatus != OPEN
// This usually takes 1 to 2 seconds
// we may not return and need to block response for a few seconds
import org.junit.Test;
import org.junit.runner.RunWith;
import org.unitils.UnitilsJUnit4TestClassRunner;

import java.util.concurrent.*;

public class DeleteThisAdHocTest {

    ExecutorService executor = Executors.newFixedThreadPool(1);

    class MyFakeTask {

        private int nrOfRetriesBeforeTaskSuccesfullyReturns;
        private int counter = 0;

        public MyFakeTask(int nrOfRetriesBeforeTaskSuccesfullyReturns) {
            this.nrOfRetriesBeforeTaskSuccesfullyReturns = nrOfRetriesBeforeTaskSuccesfullyReturns;
        public boolean isFinished() {
            return(counter > nrOfRetriesBeforeTaskSuccesfullyReturns);


    public void testFuture_timeout(){

        final MyFakeTask fakeTask = new MyFakeTask(3);
        FutureTask<String> future = new FutureTask<String>(
            new Callable<String>() {
                public String call() throws InterruptedException  {
                    while(!fakeTask.isFinished()) {
                        System.out.println("Task isn't finished yet");
                    return "Aloha!";


        String result;
            result = future.get(5, TimeUnit.SECONDS);
        } catch (ExecutionException ex){
            result = "error during execution";
        } catch (InterruptedException ie) {
            result = "interrupted";
        } catch (TimeoutException te){
            result = "timeout";
        } finally {

When running the code above, this results in the following output:

Task isn't finished yet
Task isn't finished yet
Task isn't finished yet