У меня есть CompletableFuture, который заблокирован в другом потоке, что-то вроде:
Код: Выделить всё
Supplier one = () -> CompletableFuture.supplyAsync(() -> {
System.out.println("started cf");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(3));
System.out.println("done cf");
return "";
});
ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(() -> {
try {
future = one.get();
future.get();
} catch (Exception e) {
System.out.println("caught");
future.completeExceptionally(e);
}
});
Код: Выделить всё
static CompletableFuture future;
public static void main(String[] args) {
Supplier one = () -> CompletableFuture.supplyAsync(() -> {
System.out.println("started cf");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(3));
System.out.println("done cf");
return "";
});
ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(() -> {
try {
future = one.get();
future.get();
} catch (Exception e) {
System.out.println("caught");
future.completeExceptionally(e);
}
});
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
future.cancel(true);
System.out.println("before join");
String s = future.join();
System.out.println("s value : " + s);
System.out.println("done");
}
Еще более удивительно, если я изменю свой код на (вместо String s = Future.join();):
Код: Выделить всё
String s = null;
try {
s = future.join();
} catch(Exception e) {
System.out.println("here : " + e.getClass());
}
Подробнее здесь: https://stackoverflow.com/questions/785 ... erstanding
Мобильная версия