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);
}
}
Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/uTe8c-dLT2Y/12975