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

03.01.2011
| 4010 views |
  • 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.*;

@RunWith(UnitilsJUnit4TestClassRunner.class)
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() {
            counter++;
            return(counter > nrOfRetriesBeforeTaskSuccesfullyReturns);
        }

    }

    @Test
    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");
                        Thread.sleep(1000);
                    }
                    return "Aloha!";
                }
            });

        executor.execute(future);

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


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
Aloha!