Skip to content

Instantly share code, notes, and snippets.

@Bill Bill/FutureTest.java
Created Oct 17, 2018

Embed
What would you like to do?
Java Future Test
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureTest {
private Callable<Integer> f1 = () -> {
System.out.println("+");
Thread.sleep(1000);
System.out.println("-");
return 1;
};
private FutureTask<Integer> t;
@Before
public void before() {
t = new FutureTask<>(f1);
}
@Test
public void testShouldTimeOut() throws Exception {
t.run();
t.get(100, TimeUnit.MILLISECONDS);
throw new AssertionError("should have timed out but didn't");
}
@Test
public void testShouldNotTimeOut() throws Exception {
try {
t.run();
t.get(2000, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new AssertionError("should not have timed out but did");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.