Spring源码情操陶冶-任务定时器ConcurrentTaskScheduler
承接前文Spring源码情操陶冶#task:scheduled-tasks解析器,本文在前文的基础上讲解单核心线程线程池的工作原理
应用附例
承接前文的例子,如下
<!--define bean for schedule task-->
<bean id="taskBean" class="com.jing.test.spring.task.TaskBean"></bean>
<task:scheduled-tasks>
<task:scheduled ref="taskBean" method="doInit" cron="0 0 0 ? * *"></task:scheduled>
<task:scheduled ref="taskBean" method="doClear" cron="0 0 23 ? * *"></task:scheduled>
</task:scheduled-tasks>
即我们不配置task:scheduled-tasks的属性scheduler,则会采取org.springframework.scheduling.concurrent.ConcurrentTaskScheduler任务定时器。
实例化缘由
可以直接去看前文的ContextLifecycleScheduledTaskRegistrar#scheduleTasks()的一个代码片段,如下
protected void scheduleTasks() {
****
****
// 如果不指定scheduler属性,则默认使用单线程池模型
if (this.taskScheduler == null) {
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
}
****
}
我们可以观察下该定时器所包含的线程池对象,调用的是JDK Executors的静态方法newSingleThreadScheduledExecutor()方法
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
直接去看ScheduledThreadPoolExecutor构造函数
public ScheduledThreadPoolExecutor(int corePoolSize) {
// 应用ThreadPoolExecutor的构造方法,这里很熟悉了
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
从上面看出,创建的线程池类型为ScheduledThreadPoolExecutor,其内部情况如下
- 核心线程-1个
- 最大可创建线程-Integer.MAX_VALUE
- 空闲线程活动时间-0秒
- 线程队列-DelayedWorkQueue
- 拒绝策略-AbortPolicy(抛异常信息)
定时器执行入口
由前文得知,定时器会根据任务的类型执行TaskScheduler接口的scheduleAtFixedRate()或者scheduleWithFixedDelay()抑或是schedule()方法。为了方便理解,我们就拿schedule()方法入手
ConcurrentTaskScheduler#schedule()
@Override
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
try {
// jdk1.8不支持,jdk1.7支持
if (this.enterpriseConcurrentScheduler) {
return new EnterpriseConcurrentTriggerScheduler().schedule(decorateTask(task, true), trigger);
}
else {
// ErrorHandler一般为LoggingErrorHandler,打印错误日志,也可以直接抛出异常
ErrorHandler errorHandler = (this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();
}
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
}
}
由上述代码可知,最后包装为ReschedulingRunnable类来调用schedule()方法,OK,在此之前我们必须好好观察下ReschedulingRunnable
ReschedulingRunnable
首先看下其UML类图

再看下其构造函数
/**
* @param delegate ScheduledMethodRunnable.class Object
*
* @param trigger 一般为CronTrigger
*
* @param executor ScheduledThreadPoolExecutor.class Object
*
* @param errorHandler 一般为LoggingErrorHandler.class Object
*
*/
public ReschedulingRunnable(Runnable delegate, Trigger trigger, ScheduledExecutorService executor, ErrorHandler errorHandler) {
// 由父类保存真实的Runnable对象
super(delegate, errorHandler);
this.trigger = trigger;
this.executor = executor;
}
- 然后直接看下
schedule()方法的代码
public ScheduledFuture<?> schedule() {
synchronized (this.triggerContextMonitor) {
// 计算下一次执行的时间
this.scheduledExecutionTime = this.trigger.nextExecutionTime(this.triggerContext);
if (this.scheduledExecutionTime == null) {
return null;
}
// 由上述的执行时间计算需要延迟的时间,精确到毫秒
long initialDelay = this.scheduledExecutionTime.getTime() - System.currentTimeMillis();
// 由ScheduledThreadPoolExecutor执行定时任务
this.currentFuture = this.executor.schedule(this, initialDelay, TimeUnit.MILLISECONDS);
return this;
}
}
- 为了理解方便,我们不直接跳至
ScheduledThreadPoolExecutor看源码,我们脑壳想想,肯定会调用其中的run()方法
@Override
public void run() {
Date actualExecutionTime = new Date();
// 调用委托类DelegatingErrorHandlingRunnable的run方法
super.run();
// 更新时间戳并回调shedule()方法使其能周期性执行任务
Date completionTime = new Date();
synchronized (this.triggerContextMonitor) {
this.triggerContext.update(this.scheduledExecutionTime, actualExecutionTime, completionTime);
if (!this.currentFuture.isCancelled()) {
schedule();
}
}
}
直接看下父类DelegatingErrorHandlingRunnable#run()方法
@Override
public void run() {
try {
this.delegate.run();
}
catch (UndeclaredThrowableException ex) {
this.errorHandler.handleError(ex.getUndeclaredThrowable());
}
catch (Throwable ex) {
this.errorHandler.handleError(ex);
}
}
上述的代码则会去执行委托类ScheduledMethodRunnable的run()方法,脑壳想想就是通过JDK的method.invoke(Object obj,Object.. args)方法执行我们自定义写的业务。并由errorHandler捕获异常进行善后,默认只是进行error级别的日志输出。
- 对此类作下小结
执行定时器最终调用
ScheduledThreadPoolExecutor#schedule()方法,并返回ScheduledFuture对象其
run()方法最终会调用ScheduledMethodRunnable对象来执行用户自定义的业务其
run()方法也会调用schedule()方法来重复执行第一点的步骤以达到定时执行的效果
ConcurrentTaskScheduler如何保证单线程活跃执行任务
我们从上文得知,其corePoolSize=1,最终原因我们需要从ScheduledThreadPoolExecutor这个继承了ThreadPoolExecutor通用线程池类来了解
ScheduledThreadPoolExecutor#schedule()
直接看下源码
public ScheduledFuture<?> schedule(Runnable command,
long delay,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
// 直接返回ScheduledFutureTask对象
RunnableScheduledFuture<?> t = decorateTask(command,
new ScheduledFutureTask<Void>(command, null,
triggerTime(delay, unit)));
// 延迟执行策略,继续追踪
delayedExecute(t);
return t;
}
继续追踪delayedExecute()方法
private void delayedExecute(RunnableScheduledFuture<?> task) {
// 如果线程池关闭了则直接拒绝任务
if (isShutdown())
reject(task);
else {
// 优先将任务放入DelayQueue队列
super.getQueue().add(task);
// 保护策略,避免添加到队列后线程池关闭了,尝试删除任务
if (isShutdown() &&
!canRunInCurrentRunState(task.isPeriodic()) &&
remove(task))
task.cancel(false);
else
// 确保已有线程在跑
ensurePrestart();
}
}
继续追踪ensurePrestart()方法
void ensurePrestart() {
int wc = workerCountOf(ctl.get());
if (wc < corePoolSize)
addWorker(null, true);
else if (wc == 0)
addWorker(null, false);
}
由上述的源码我们可以得知
当线程池数小于执行的核心线程数
corePoolSize,则会创建线程,不管核心与否我们都可以得知一旦当前线程数>=核心线程数,则不会进行新线程的创建
ConcurrentTaskScheduler指定的corePoolSize=1,由第一点得知,永远只有一个线程存在于线程池中
ConcurrentTaskScheduler如何保证任务延迟指定时长后被执行
为了避免大片的源码影响我们的阅读以及理解,博主只在此处指出ConcurrentTaskScheduler所拥有DelayQueue队列的take()方法实现了延迟等待的效果
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
// 可重入同步锁,确保该方法线程安全
lock.lockInterruptibly();
try {
for (;;) {
E first = q.peek();
// 队列无任务,那就处于休眠等待
if (first == null)
available.await();
else {
// 获取还需等待的时间
long delay = first.getDelay(NANOSECONDS);
if (delay <= 0)
return q.poll();
first = null; // don't retain ref while waiting
if (leader != null)
available.await();
else {
Thread thisThread = Thread.currentThread();
leader = thisThread;
try {
// 等待相应的时间后才可放行,采取的是Condition的机制
available.awaitNanos(delay);
} finally {
if (leader == thisThread)
leader = null;
}
}
}
}
} finally {
// 唤醒等待的线程或者等待的条件
if (leader == null && q.peek() != null)
available.signal();
lock.unlock();
}
}
上述代码用到了可重入锁以及锁条件Condition的相关知识,后续会详细分析锁的相关知识。此处作下总结
ReentrantLock锁为可重入锁,即相同的线程可再次获取该锁,不必等待阻塞
ReentrantLock的Condition机制,其类似于Object.wait()机制其调用
available.awaitNanos(delay);方法使当前线程休眠指定的时间后,最终会调用q.poll()方法返回待处理的任务有兴趣的读者可自行阅读
ThreadPoolExecutor的runWorker()方法和getTask()方法,便可以彻底理解ScheduledThreadPoolExecutor的定时机制
小结
CocurrentTaskScheduler指定的单线程模型,会让任务按照FIFO的机制有序的被执行,这个模型不大适合多个任务的同时定时执行,会导致任务执行有一定的延迟性。所以建议与spring结合时配置task:scheduler并配置pool-size属性
Spring源码情操陶冶-任务定时器ConcurrentTaskScheduler的更多相关文章
- Spring源码情操陶冶#task:scheduled-tasks解析器
承接前文Spring源码情操陶冶#task:executor解析器,在前文基础上解析我们常用的spring中的定时任务的节点配置.备注:此文建立在spring的4.2.3.RELEASE版本 附例 S ...
- Spring源码情操陶冶-AbstractApplicationContext#finishBeanFactoryInitialization
承接前文Spring源码情操陶冶-AbstractApplicationContext#registerListeners 约定web.xml配置的contextClass为默认值XmlWebAppl ...
- Spring源码情操陶冶-AbstractApplicationContext#registerListeners
承接前文Spring源码情操陶冶-AbstractApplicationContext#onRefresh 约定web.xml配置的contextClass为默认值XmlWebApplicationC ...
- Spring源码情操陶冶-AbstractApplicationContext#onRefresh
承接前文Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster 约定web.xml配置的contextClass ...
- Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster
承接前文Spring源码情操陶冶-AbstractApplicationContext#initMessageSource 约定web.xml配置的contextClass为默认值XmlWebAppl ...
- Spring源码情操陶冶-AbstractApplicationContext#initMessageSource
承接前文Spring源码情操陶冶-AbstractApplicationContext#registerBeanPostProcessors 约定web.xml配置的contextClass为默认值X ...
- Spring源码情操陶冶-AbstractApplicationContext#registerBeanPostProcessors
承接前文Spring源码情操陶冶-AbstractApplicationContext#invokeBeanFactoryPostProcessors 瞧瞧官方注释 /** * Instantiate ...
- Spring源码情操陶冶-AbstractApplicationContext#invokeBeanFactoryPostProcessors
阅读源码有利于陶冶情操,承接前文Spring源码情操陶冶-AbstractApplicationContext#postProcessBeanFactory 约定:web.xml中配置的context ...
- Spring源码情操陶冶-AbstractApplicationContext#postProcessBeanFactory
阅读源码有利于陶冶情操,承接前文Spring源码情操陶冶-AbstractApplicationContext#prepareBeanFactory 约定:web.xml中配置的contextClas ...
随机推荐
- Spring Boot入门教程1、使用Spring Boot构建第一个Web应用程序
一.前言 什么是Spring Boot?Spring Boot就是一个让你使用Spring构建应用时减少配置的一个框架.约定优于配置,一定程度上提高了开发效率.https://zhuanlan.zhi ...
- linux --> vimrc的配置
vimrc的配置 .vimrc文件: " 去掉讨厌的有关vi一致性模式,避免以前版本的一些bug和局限 set nocompatible "代码补全 set completeopt ...
- 设计模式 --> (12)装饰模式
装饰模式 时常会遇到这样一种情况,我已经设计好了一个接口,并且也有几个实现类,但是这时我发现我设计的时候疏忽了,忘记了一些功能,或者后来需求变动要求加入一 些功能,最简单的做法就是修改接口,添加函数, ...
- Spring Boot 2.0(五):Docker Compose + Spring Boot + Nginx + Mysql 实践
我知道大家这段时间看了我写关于 docker 相关的几篇文章,不疼不痒的,仍然没有感受 docker 的便利,是的,我也是这样认为的,I know your felling . 前期了解概念什么的确实 ...
- Android开发之漫漫长途 XVI——ListView与RecyclerView项目实战
该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...
- JavaScript(第二十五天)【事件绑定及深入】
事件绑定分为两种:一种是传统事件绑定(内联模型,脚本模型),一种是现代事件绑定(DOM2级模型).现代事件绑定在传统绑定上提供了更强大更方便的功能. 一.传统事件绑定的问题 传统事件绑定有内联模型 ...
- NOIP2012 提高组 Day 2
http://www.cogs.pro/cogs/page/page.php?aid=16 期望得分:100+100+0=0 实际得分:100+20+0=120 T2线段树标记下传出错 T1 同余方程 ...
- HTML 样式设计
1.自动设置外边距 style="margin:auto auto;"
- New UWP Community Toolkit - AdaptiveGridView
概述 UWP Community Toolkit 中有一个自适应的 GridView 控件 - AdaptiveGridView,本篇我们结合代码详细讲解 AdaptiveGridView 的实现 ...
- Linux下的Shell编程(2)环境变量和局部变量
Shell Script是一种弱类型语言,使用变量的时候无需首先声明其类型. 局部变量在本地数据区分配内存进行存储,这个变量归当前的Shell所有,任何子进 程都不能访问本地变量.这些变量与环境变量不 ...