执行一段代码超时处理是比较常见的需求,比如在进行一些比较耗时的业务处理或者在占用一些比较宝贵的资源(如数据库连接),我们通常需要给这些操作设置一个超时时间,当执行时长超过设置的阈值的时候,就终止操作并回收资源,给用户一个提示,不用等到资源耗尽。
/**
* 定义实体,作为有返回值的情况
*/
public class Demo{
private int id;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
执行下面的代码进行处理
import cn.hutool.core.util.ObjectUtil;
import java.util.concurrent.*;
/**
* 处理执行一段代码,超时抛异常或结束执行
*/
public class Test {
public static void main(String[] args) {
long timeout =5000;
ExecutorService executorService = Executors.newSingleThreadExecutor();
ExecutorCompletionService<Demo> executorCompletionService = new ExecutorCompletionService<>(executorService);
Future<Demo> demoFuture = executorCompletionService.submit(new Callable<Demo>() {
@Override
public Demo call() throws Exception {
return test();
}
});
try {
Object result = executorCompletionService.poll(timeout, TimeUnit.MILLISECONDS);
if(ObjectUtil.isNull(result)){
System.out.println("超时,结束方法执行");
demoFuture.cancel(true);
throw new RuntimeException("超时,结束");
}else {
System.out.println("正常执行完成");
//todo 有返回值,就返回
Demo demo = demoFuture.get();
return;
}
} catch (Exception e) {
System.out.println("异常了,结束超");
demoFuture.cancel(true);
throw new RuntimeException(e);
}
}
/**
* 需要处理的的业务块
* @return
* @throws InterruptedException
*/
private static Demo test() throws InterruptedException {
Thread.sleep(1000);
return null;
}
}