随着业务发展的需要,总公司集团老总(Doug Lea ) 提出了能支持预定功能(scheduled)的经营模式(ScheduledExecutorService)。PS: schedule:安排,计划,预定
1.战略:ScheduledExecutorService
观摩一下其内部新增的功能
- schedule(Runnable/Callale, delay, TimeUnit ):在指定延迟之后执行一次(one-shot)任务
- scheduleAtFixedRate(Runnable , initialDelay, period,TimeUnit ):在initDelay后,以period的固定间隔执行任务
- scheduleWithFixedDelay(Runnable , initialDelay, delay, TimeUnit ):在initDelay后,以固定的delay延时执行任务
根据上面的描述,我们可以发现ScheduledExecutorService主要推出的功能是:延时,定时,周期性服务、。
2.战术:ScheduledThreadPoolExecutor
正所谓“万变不离其宗”,新模式(**ScheduledExecutorService)**也是基于旧模式(ThreadPoolExecutor)而来的。都说“青出于蓝而胜于蓝”,不过眼见为实…
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
public ScheduledThreadPoolExecutor(int corePoolSize,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), handler);
}
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory, handler);
}
通过上面的构造函数(经营模板),我们会发现,总公司应该是结合以往的经验,对新模式进行了比较大的优化。
- 必须指定正式工(corePoolSize);
- 临时工的数量无限制(maxiumPoolSize = Integer.MAX_VALUE),结合成本只能keepAliveTime = 0.
- 排队方式(使用DelayedWorkQueue)进行优化. (PS:初始容量为16,基于数据结构堆(heap-based)而设计,加速离队速度(O(n) -> O(log n)),减少城管的骚扰(减少垃圾回收)
- 开放拒绝策略(RejectedExecutionHandler)
- 支持选择厨师培训学校(ThreadFactory)
3. 实施:Executors
如果普通客户来连锁店,一般都会来找Executors…只此一家,别无分店.
/** Cannot instantiate. 不能实例化
*/
private Executors() {}
着重强调一下:Executors一般都只会开放corePoolSize,ThreadFactory两个选项。
为客户着想使我们应该做的,
单厨师套餐
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1, threadFactory));
}
多厨师套餐
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
后面我们会专门出一篇来讲总代理(Executors)以及VIP客户定制化,圆你一个开店做老板的梦…