代码超过指定时间直接抛TimeoutException
public class TimeoutUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(TimeoutUtil.class);
public static <T> T doWithCallableTimeout(Callable<T> task, long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<T> future = executor.submit(task);
try {
return future.get(timeout, unit); // 这里设置超时时间
} catch (TimeoutException | InterruptedException | ExecutionException e) {
future.cancel(true); // 如果超时,尝试取消任务
LOGGER.error("任务执行超时或发生异常", e);
throw e;
} finally {
executor.shutdownNow(); // 关闭线程池
}
}
public static void doWithRunnableTimeout(Runnable task, long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(task);
try {
future.get(timeout, unit); // 这里设置超时时间
} catch (TimeoutException | InterruptedException | ExecutionException e) {
future.cancel(true); // 如果超时,尝试取消任务
LOGGER.error("任务执行超时或发生异常", e);
throw e;
} finally {
executor.shutdownNow(); // 关闭线程池
}
}
}