Java中调度线程池ScheduledThreadPoolExecutor原理探究

一、 前言

前面讲解过Java中线程池ThreadPoolExecutor原理探究,ThreadPoolExecutor是Executors中一部分功能,下面来介绍另外一部分功能也就是ScheduledThreadPoolExecutor的实现,后者是一个可以在一定延迟时候或者定时进行任务调度的线程池。

二、 类图结构

 

Executors其实是个工具类,里面提供了好多静态方法,根据用户选择返回不同的线程池实例。
ScheduledThreadPoolExecutor继承了ThreadPoolExecutor并实现ScheduledExecutorService接口,关于ThreadPoolExecutor的介绍可以参考:
http://www.jianshu.com/p/3cc67876375f
线程池队列是DelayedWorkQueue,它是对delayqueue的优化,关于delayqueue参考:http://www.jianshu.com/p/2659eb72134b
ScheduledFutureTask是阻塞队列元素是对任务修饰。

构造函数:

 //使用改造后的delayqueue.
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}

三、一个例子

// 任务间以固定时间间隔执行,延迟1s后开始执行任务,任务执行完毕后间隔2s再次执行,任务执行完毕后间隔2s再次执行,依次往复
static void scheduleWithFixedDelay() throws InterruptedException, ExecutionException {
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10); ScheduledFuture<?> result = executorService.scheduleWithFixedDelay(new Runnable() {
public void run() { System.out.println(System.currentTimeMillis()); }
}, 1000, 2000, TimeUnit.MILLISECONDS); // 由于是定时任务,一直不会返回
result.get();
System.out.println("over"); }
// 相对开始加入任务的时间点固定频率执行:从加入任务开始算1s后开始执行任务,1+2s开始执行,1+2*2s执行,1+n*2s开始执行;
// 但是如果执行任务时间大约2s则不会并发执行后续任务将会延迟。 static void scheduleAtFixedRate() throws InterruptedException, ExecutionException {
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10); ScheduledFuture<?> result = executorService.scheduleAtFixedRate(new Runnable() {
public void run() { System.out.println(System.currentTimeMillis()); }
}, 1000, 2000, TimeUnit.MILLISECONDS); // 由于是定时任务,一直不会返回
result.get();
System.out.println("over");
} // 延迟1s后开始执行,只执行一次,没有返回值
static void scheduleRunable() throws InterruptedException, ExecutionException {
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10); ScheduledFuture<?> result = executorService.schedule(new Runnable() { @Override
public void run() {
System.out.println("gh");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}, 1000, TimeUnit.MILLISECONDS); System.out.println(result.get()); } // 延迟1s后开始执行,只执行一次,有返回值
static void scheduleCaller() throws InterruptedException, ExecutionException {
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10); ScheduledFuture<String> result = executorService.schedule(new Callable<String>() { @Override
public String call() throws Exception { try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return "gh";
} }, 1000, TimeUnit.MILLISECONDS); // 阻塞,直到任务执行完成
System.out.print(result.get()); }

三、 源码分析

3.1 schedule(Runnable command, long delay,TimeUnit unit)方法

public ScheduledFuture<?> schedule(Runnable command,
long delay,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException(); //装饰任务,主要实现public long getDelay(TimeUnit unit)和int compareTo(Delayed other)方法
RunnableScheduledFuture<?> t = decorateTask(command,
new ScheduledFutureTask<Void>(command, null,
triggerTime(delay, unit)));
//添加任务到延迟队列
delayedExecute(t);
return t;
} private void delayedExecute(RunnableScheduledFuture<?> task) { //如果线程池关闭了,则拒绝任务
if (isShutdown())
reject(task);
else {
//添加任务到队列
super.getQueue().add(task); //再次检查线程池关闭
if (isShutdown() &&
!canRunInCurrentRunState(task.isPeriodic()) &&
remove(task))
task.cancel(false);
else
//确保至少一个线程在处理任务,即使核心线程数corePoolSize为0
ensurePrestart();
}
} void ensurePrestart() {
int wc = workerCountOf(ctl.get());
//增加核心线程数
if (wc < corePoolSize)
addWorker(null, true);
//如果初始化corePoolSize==0,则也添加一个线程。
else if (wc == 0)
addWorker(null, false);
}

上面做的首先吧runnable装饰为delay队列所需要的格式的元素,然后把元素加入到阻塞队列,然后线程池线程会从阻塞队列获取超时的元素任务进行处理,下面看下队列元素如何实现的。

//r为被修饰任务,result=null,ns为当前时间加上delay时间后的
ScheduledFutureTask(Runnable r, V result, long ns) {
super(r, result);
this.time = ns;
this.period = 0;
this.sequenceNumber = sequencer.getAndIncrement();
} //通过适配器把runnable转换为callable
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
} long triggerTime(long delay, TimeUnit unit) {
return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
}

关于FutureTask可以参考 http://www.jianshu.com/p/49541d720d5b
修饰后把当前任务修饰为了delay队列所需元素,下面看下元素的两个重要方法:

  • 过期时间计算

    //元素过期算法,装饰后时间-当前时间,就是即将过期剩余时间
    public long getDelay(TimeUnit unit) {
    return unit.convert(time - now(), TimeUnit.NANOSECONDS);
    }
  • 元素比较
    public int compareTo(Delayed other) {
    if (other == this) // compare zero ONLY if same object
    return 0;
    if (other instanceof ScheduledFutureTask) {
    ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
    long diff = time - x.time;
    if (diff < 0)
    return -1;
    else if (diff > 0)
    return 1;
    else if (sequenceNumber < x.sequenceNumber)
    return -1;
    else
    return 1;
    }
    long d = (getDelay(TimeUnit.NANOSECONDS) -
    other.getDelay(TimeUnit.NANOSECONDS));
    return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

schedule(Callable<V> callable,
long delay,
TimeUnit unit)和schedule(Runnable command, long delay,TimeUnit unit)类似。

compareTo作用是在加入元素到dealy队列时候进行比较,需要调整堆让最快要过期的元素放到队首。所以无论什么时候向队列里面添加元素,队首的都是最即将过期的元素。

3.2 scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)

定时调度:相邻任务间时间固定

    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
if (delay <= 0)
throw new IllegalArgumentException(); //修饰包装,注意这里是period=-delay<0
ScheduledFutureTask<Void> sft =
new ScheduledFutureTask<Void>(command,
null,
triggerTime(initialDelay, unit),
unit.toNanos(-delay));
RunnableScheduledFuture<Void> t = decorateTask(command, sft);
sft.outerTask = t;
//添加任务到队列
delayedExecute(t);
return t;
}
//period为 delay时间
ScheduledFutureTask(Runnable r, V result, long ns, long period) {
super(r, result);
this.time = ns;
this.period = period;
this.sequenceNumber = sequencer.getAndIncrement();
}
我们知道任务添加到队列后,工作线程会从队列获取并移除到期的元素,然后执行run方法,所以下面看看ScheduledFutureTask的run方法如何实现定时调度的
public void run() {

    //是否只执行一次
boolean periodic = isPeriodic(); //取消任务
if (!canRunInCurrentRunState(periodic))
cancel(false);
//只执行一次,调用schdule时候
else if (!periodic)
ScheduledFutureTask.super.run(); //定时执行
else if (ScheduledFutureTask.super.runAndReset()) {
//设置time=time+period
setNextRunTime(); //重新加入该任务到delay队列
reExecutePeriodic(outerTask);
}
}
        private void setNextRunTime() {
long p = period;
if (p > 0)
time += p;
else//由于period=-delay所以执行这里,设置time=now()+delay
time = triggerTime(-p);
}

总结:定时调度是先从队列获取任务然后执行,然后在重新设置任务时间,在把任务放入队列实现的。
如果任务执行时间大于delay时间则等任务执行完毕后的delay时间后在次调用任务,不会同一个任务并发执行。

3.3 scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)

定时调度:相对起始时间点固定频率调用

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
if (period <= 0)
throw new IllegalArgumentException();
//装饰任务类,注意period=period>0,不是负的
ScheduledFutureTask<Void> sft =
new ScheduledFutureTask<Void>(command,
null,
triggerTime(initialDelay, unit),
unit.toNanos(period));
RunnableScheduledFuture<Void> t = decorateTask(command, sft);
sft.outerTask = t;
//添加任务到队列
delayedExecute(t);
return t;
}
        private void setNextRunTime() {
long p = period;
//period=delay;
if (p > 0)
time += p;//由于period>0所以执行这里,设置time=time+delay
else
time = triggerTime(-p);
}

总结:相对于上面delay,rate方式执行规则为时间为initdelday + n*period;时候启动任务,但是如果当前任务还没有执行完,要等到当前任务执行完毕后在执行一个任务。

四、 总结

调度线程池主要用于定时器或者延迟一定时间在执行任务时候使用。内部使用优化的DelayQueue来实现,由于使用队列来实现定时器,有出入队调整堆等操作,所以定时并不是非常非常精确。

线程池ScheduledThreadPoolExecutor的更多相关文章

  1. Java调度线程池ScheduledThreadPoolExecutor源码分析

    最近新接手的项目里大量使用了ScheduledThreadPoolExecutor类去执行一些定时任务,之前一直没有机会研究这个类的源码,这次趁着机会好好研读一下. 该类主要还是基于ThreadPoo ...

  2. Java并发包源码学习系列:线程池ScheduledThreadPoolExecutor源码解析

    目录 ScheduledThreadPoolExecutor概述 类图结构 ScheduledExecutorService ScheduledFutureTask FutureTask schedu ...

  3. JUC 并发编程--09, 阻塞队列: DelayQueue, PriorityBlockingQueue ,SynchronousQueue, 定时任务线程池: ScheduledThreadPoolExecutor

    先看DelayQueue 这个是用优先级队列实现的无界限的延迟队列,直接上代码: /** * 这个是 {@link DelayQueue} 延时队列 的验证使用类 */ class MyDelayed ...

  4. Netty核心概念(7)之Java线程池

    1.前言 本章本来要讲解Netty的线程模型的,但是由于其是基于Java线程池设计而封装的,所以我们先详细学习一下Java中的线程池的设计.之前也说过Netty5被放弃的原因之一就是forkjoin结 ...

  5. Executor线程池只看这一篇就够了

    线程池为线程生命周期的开销和资源不足问题提供了解决方 案.通过对多个任务重用线程,线程创建的开销被分摊到了多个任务上. 线程实现方式 Thread.Runnable.Callable //实现Runn ...

  6. ElasticSearch 线程池类型分析之 ResizableBlockingQueue

    ElasticSearch 线程池类型分析之 ResizableBlockingQueue 在上一篇文章 ElasticSearch 线程池类型分析之 ExecutorScalingQueue的末尾, ...

  7. JUC 一 线程池

    线程 线程,是程序执行的最小单元.线程是进程中的其中一个实体,是被系统独立调度和分派的基本单位 它可与同属一个进程的其它线程共享进程所拥有的全部资源. 一个线程可以创建和撤消另一个线程,同一进程中的多 ...

  8. 硬核干货:4W字从源码上分析JUC线程池ThreadPoolExecutor的实现原理

    前提 很早之前就打算看一次JUC线程池ThreadPoolExecutor的源码实现,由于近段时间比较忙,一直没有时间整理出源码分析的文章.之前在分析扩展线程池实现可回调的Future时候曾经提到并发 ...

  9. java线程池趣味事:这不是线程池

    要想写出高性能高并发的应用,自然有许多关键,如io,算法,异步,语言特性,操作系统特性,队列,内存,cpu,分布式,网络,数据结构,高性能组件. 胡说一通先. 回到主题,线程池.如果说多线程是提高系统 ...

随机推荐

  1. 【真】CSP2019退役记(upd:12.21)

    这是第一次CSP(Counter-Strike Professor),也是最后一次. Day-1 上午考试,日常被虐. 下午颓mc Day0 上午考试,日常被虐. 下午颓mc 晚上看了下悬线法.最小表 ...

  2. npm err! Unexpected end of JSON input while parsing near解决办法

    npm install时出现npm err! Unexpected end of JSON input while parsing near错误 输入  npm cache clean --fore ...

  3. vue-awesome-swiper兼容ie9

    轮播插件vue-awesome-swiper在ie9中运行的时候没效果 解决方法: vue-awesome-swiper在IE9下报错, 主要原因是element.classlist.add()方法在 ...

  4. 汽车制造商表态:必须依靠MES系统来管控流程

    汽车行业特点 汽车工业是一个高投入,高产出,集群式发展的产业部门. 汽车自身的投资,生产,研发,供应,销售,维修:前序的原材料,零部件,技术装备,物流:后序的油料,服务,信贷,咨询,保险,直至基础设施 ...

  5. Java深入学习(6):Disruptor

    Disruptor框架简介: 并发框架,基于事件驱动,使用观察者模式 底层采用环形数组,取模算法 简单使用: /** * 声明一个Event:表示生产者和消费者之间传递的数据类型 */ public ...

  6. 05-Vue组件

    定义Vue组件 什么是组件: 组件的出现,就是为了拆分Vue实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可: 组件化和模块化的不同: ...

  7. 使用nginx 做kbmmw REST 服务的负载均衡

    我们一般在云上部署REST服务.既想利用kbmmw 的方便性,又想保证系统的安全性,同时 想通过负载均衡保证服务器的健壮性.下面我们使用ubuntu+nginx 来实现以下kbmmw rest 服务器 ...

  8. FormData使用方法详解

    FormData的主要用途有两个: 1.将form表单元素的name与value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率. 2.异步上传文件 一.创建formData对象 ...

  9. k8s 挂载卷介绍(四)

    kubernetes关于pod挂载卷的知识 首先要知道卷是pod资源的属性,pv,pvc是单独的资源.pod 资源的volumes属性有多种type,其中就包含有挂载pvc的类型.这也帮我理清了之间的 ...

  10. commix 命令注入工具

    关于系统命令注入,可以参考这篇文章:命令攻击介绍 系统命令注入场景 在对企业进行安全测试时候,很少会发现系统注入漏洞.这是因为大部分情况下代码业务主要是数据操作.文件操作.逻辑处理和api接口调用等, ...