Error
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.

nrofretriesbeforetasksuccesfullyreturns

Use a FutureTask to block processing while waiting for an asynchronous call to return
Tuesday, 01 March 2011 05:42
// #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 future = new FutureTask(
new Callable() {
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!

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/uTe8c-dLT2Y/12975

 


Taxonomy by Zaragoza Online