我有以下代码片段:
@Async("executor")
public CompletableFuture<List<SecondObject>> getSecondObject(List<FirstObject> firstObject) {
CompletableFuture<List<SecondObject>> future = new CompletableFuture<>();
final int timeout = 5000;
Timer timer = new Timer();
//Thread created by configuration
final Thread executorThread = Thread.currentThread();
//Method responsible for thread interruption
final TimerTask interruptTask = new TimerTask() {
@Override
public void run() {
Thread timerTaskThread = Thread.currentThread();
System.out.println("Exception for thread "+executorThread.getName()+" is thrown");
System.out.println("Timer task thread "+timerTaskThread.getName()+" is issued");
executorThread.interrupt();
future.completeExceptionally(new InterruptedException());
}
};
//Schedule set for thread interruption
timer.schedule(interruptTask, timeout);
System.out.println("Thread " + Thread.currentThread().getName() + " is created.");
System.out.println("Thread " + Thread.currentThread().getName() + " is executing a task.");
List<SecondObject> secondObject = Collections.emptyList();
for (int i = 0; i < 5; i++) {
i--;
}
future.complete(secondObject));
timer.cancel();
System.out.println("Thread " + Thread.currentThread().getName() + " has been terminated.");
return future;
}
}
和试图访问
CompletableFuture
的代码。
List<FirstObject> firstObject = Collections.emptyList();
List<SecondObject> testedList = null;
CompletableFuture<List<SecondObject>> future = sectionsService.getSecondObject(firstObject);
try {
testedList = future.get();
} catch (InterruptedException | ExecutionException e) {
}
我遇到的问题是,当我调用
get()
方法时,尽管每个 TimerTask
都跟踪用 @Async
创建的每个新线程的超时,无限任务(这里是无限的 for loop
)完全阻塞主线程. @Async
线程的中断标志被抛出,但线程本身并未停止 - 尽管线程被中断,程序仍无限执行 for loop
。程序一直等到 get()
返回一些东西。我需要TimerTask
在超过超时时实际停止线程。
future.get(long timeout, TimeUnit unit);