java 开发中经常遇到需要对线程、线程池、接口调用进行超时控制的需求,这种需求的场景往往是存在响应时间较长的接口或者方法,进行超时控制,避免因调用时间过长,影响调用者本身的性能甚至可用性,下面简单讨论下这些场合里超时控制的方法和工具。
1. Future 接口
Future接口是Java标准API的一部分,在java.util.concurrent包中,配合有返回值的线程使用。使用较多的方法有future.get(),future.get(long timeout, TimeUnit unit),注意get方法是一个同步方法,Futrue对象可以监视目标线程调用call的情况,当你调用Future的get()方法以获得结果时,当前线程就开始阻塞,直接call方法结束返回结果,一般推荐使用future.get(long timeout, TimeUnit unit)。
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Result> work = new Callable<Result>() {
@Override
public Result call() {
// do something
return result
}
};
Future<Result> future = executor.submit(work);
try {
result = future.get(TIMEOUT, TIMEUNIT);
} catch (TimeoutException e) {
...
} catch (...) {
...
}
2. Guava SimpleTimeLimiter
SimpleTimeLimiter 实现了TimeLimiter,本质是对Future的封装,