线程池中如何控制超时时间?

 

线程池构造方法不能控制任务的超时时间

 java.util.concurrent.ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, java.util.concurrent.TimeUnit, java.util.concurrent.BlockingQueue<java.lang.Runnable>)

 long, java.util.concurrent.TimeUnit设置的是超过core数量的线程在没有任务时最大的idleTime

 

但是执行任务时可以使用Future类来控制超时时间

AbstractExecutorService中invokeAll,invokeAny可以指定超时时间 (没有完成的task会被cancel,并抛出interrupted异常), 但其本质还是使用Future.cancle()/get(long timeout, TimeUnit unit)

这里不是对单个task的超时控制

 

 

 

 另起一个SchedulerThread监控FutureTask是否超时,@Hystrix的超时原理

http://westyi.iteye.com/blog/714935

 cancle不一定成功,无法判端里面的事务是否真的失败, 只是在确定超时后 返回了一个备用对象

 

Executors 返回的线程池对象的弊端如下:

1)FixedThreadPool 和 SingleThreadPool: 允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM

2)CachedThreadPool 和 ScheduledThreadPool: 允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM

 

 

 

线程Thread

线程工厂 ThreadFactory

线程池  正确的概念是指ThreadPoolExecutor,  注意父类AbstractExecutorService, ExecutorService中超时方法的使用

 

posted @ 2018-08-21 11:44  funny_coding  阅读(18850)  评论(0编辑  收藏  举报
build beautiful things, share happiness