处理执行一段代码,超时抛异常或结束执行

执行一段代码超时处理是比较常见的需求,比如在进行一些比较耗时的业务处理或者在占用一些比较宝贵的资源(如数据库连接),我们通常需要给这些操作设置一个超时时间,当执行时长超过设置的阈值的时候,就终止操作并回收资源,给用户一个提示,不用等到资源耗尽。

/**
 * 定义实体,作为有返回值的情况
 */
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;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值