监控某个线程异常导致整个线程池奔溃的问题

import java.util.concurrent.ExecutorService;

@Service
public class TestService{

private ExecutorService executorService;

//第一步:定义一个外部线程池
@PostConstruct
public void init() {
	//定义线程池
    int poolSize = Runtime.getRuntime().availableProcessors() * 2;
    executorService = new ThreadPoolExecutor(poolSize, poolSize,
            0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1024), // 使用有界队列,避免OOM
            new ThreadPoolExecutor.DiscardPolicy());
}

//第二步:定义一个内部线程池类,
//通过设置时间段,来监控回调函数s在一定时间内未返回,则认为此函数异常,此时抛出该异常,释放当前线程,避免因为某个线程一直不释放导致整体线程池出问题
private static class Wait {
	//线程池
	private static ForkJoinPool pool = new ForkJoinPool();
	//参数:①s:回调函数,即执行逻辑 ②要等待时间的数字:1,2,10等等 ③时间的类型:时分秒等等
	//返回值:是参数s对应函数的返回值
	public static <T> T wait(Supplier<T> s, int t, TimeUnit unit) throws Exception{
		CompletableFuture<T> f = CompletableFuture.supplyAsync(s, pool);
		return f.get(t,  unit);
	}
}

//第三步:编写具体的代码执行逻辑
//具体的执行代码逻辑
public void queryDataNew(){
	try{
		
		//若20分钟内,该方法未返回,则认为出现异常
		List<String> resultList = Wait.wait(() -> {
			//如果需要外部参数,则使用AtomicReference类的get和set方法即可
            List<String> userList = new ArrayList<>();
			userList.add("1");
			userList.add("2");
			userList.add("3");
			//代码逻辑
			...
			return userList;
        },20, TimeUnit.MINUTES);
		return resultList;
	}catch(Exception e){
		e.printStackTrace();
		throw new RuntimeException("自定义异常:"+e.getMessage());
	}finally{
		//无论程逻辑是否报错,都需要执行的逻辑,可无
	}
}

//第四步:测试的整体代码逻辑
public void test(){
	executorService.submit(() -> {
		this.queryDataNew();
	});
	System.out.println("方法调用");
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值