Skip to content

Instantly share code, notes, and snippets.

@jhsea3do
Created February 3, 2020 02:35
Show Gist options
  • Save jhsea3do/d1cbd68b604ef5f4e32e5753310a0031 to your computer and use it in GitHub Desktop.
Save jhsea3do/d1cbd68b604ef5f4e32e5753310a0031 to your computer and use it in GitHub Desktop.
Java Future Cancel / Timeout
package study.future;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureMain {
public static Callable<String> newCallable = () -> {
String content = null;
while (true) {
Thread.sleep(2000);
if (Thread.currentThread().isInterrupted()) {
System.err.println("thread interrupted");
content = "NO";
break;
} else {
content = "OK";
break;
}
}
return content;
};
public static void main(String... args) {
long ts = System.currentTimeMillis();
ExecutorService es = Executors.newFixedThreadPool(2);
Future<String> fu = es.submit(newCallable);
boolean testCancel = false;
boolean testTimeout = false;
// while(!fu.isDone()) {
//
// }
String result = null;
try {
Thread t = new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("do:cancel");
fu.cancel(true);
});
if (testCancel) {
t.start();
}
if (testTimeout) {
result = fu.get(1000, TimeUnit.MILLISECONDS);
} else {
result = fu.get();
}
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
System.err.println("e:" + e.getClass());
} catch (CancellationException e) {
System.err.println("e:" + e.getClass());
}
System.out.println("r:" + result);
es.shutdown();
long te = System.currentTimeMillis();
System.out.println("t:" + (te - ts));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment