Java Concurrency - ScheduledThreadPoolExecutor
The Executor framework provides the ThreadPoolExecutor class to execute Callable and Runnable tasks with a pool of threads, which avoid you all the thread creation operations. When you send a task to the executor, it's executed as soon as possible, according to the configuration of the executor. There are used cases when you are not interested in executing a task as soon as possible. You may want to execute a task after a period of time or to execute a task periodically. For these purposes, the Executor framework provides the ScheduledThreadPoolExecutor class.
/**
* This class implements the task of this example. Writes a
* message to the console with the actual date and returns the
* 'Hello, world' string
*/
public class Task implements Callable<String> { /**
* Name of the task
*/
private String name; /**
* Constructor of the class
* @param name Name of the task
*/
public Task(String name) {
this.name = name;
} /**
* Main method of the task. Writes a message to the console with
* the actual date and returns the 'Hello world' string
*/
@Override
public String call() throws Exception {
System.out.printf("%s: Starting at : %s\n", name, new Date());
return "Hello, world";
} } /**
* Main class of the example. Send 5 tasks to an scheduled executor Task 0:
* Delay of 1 second Task 1: Delay of 2 seconds Task 2: Delay of 3 seconds Task
* 3: Delay of 4 seconds Task 4: Delay of 5 seconds
*/
public class Main { /**
* Main method of the example
* @param args
*/
public static void main(String[] args) { // Create a ScheduledThreadPoolExecutor
ScheduledExecutorService executor = (ScheduledExecutorService) Executors.newScheduledThreadPool(1); System.out.printf("Main: Starting at: %s\n", new Date()); // Send the tasks to the executor with the specified delay
for (int i = 0; i < 5; i++) {
Task task = new Task("Task " + i);
executor.schedule(task, i + 1, TimeUnit.SECONDS);
} // Finish the executor
executor.shutdown(); // Waits for the finalization of the executor
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
} // Writes the finalization message
System.out.printf("Core: Ends at: %s\n", new Date());
}
}
The key point of this example is the Main class and the management of ScheduledThreadPoolExecutor. As with class ThreadPoolExecutor, to create a scheduled executor, Java recommends the utilization of the Executors class. In this case, you have to use the newScheduledThreadPool() method. You have passed the number 1 as a parameter to this method. This parameter is the number of threads you want to have in the pool.
To execute a task in this scheduled executor after a period of time, you have to use the schedule() method. This method receives the following three parameters:
- The task you want to execute
- The period of time you want the task to wait before its execution
- The unit of the period of time, specified as a constant of the TimeUnit class
In this case, each task will wait for a number of seconds (TimeUnit.SECONDS) equal to its position in the array of tasks plus one.
If you want to execute a task at a given time, calculate the difference between that date and the current date and use that difference as the delay of the task.
The following snippet shows the output of an execution of this example:
Main: Starting at: Mon Nov 07 16:39:33 CST 2016
Task 0: Starting at : Mon Nov 07 16:39:34 CST 2016
Task 1: Starting at : Mon Nov 07 16:39:35 CST 2016
Task 2: Starting at : Mon Nov 07 16:39:36 CST 2016
Task 3: Starting at : Mon Nov 07 16:39:37 CST 2016
Task 4: Starting at : Mon Nov 07 16:39:38 CST 2016
Core: Ends at: Mon Nov 07 16:39:38 CST 2016
You can see how the tasks start their execution one per second. All the tasks are sent to the executor at the same time, but each one with a delay of 1 second later than the previous task.
You can also use the Runnable interface to implement the tasks, because the schedule() method of the ScheduledThreadPoolExecutor class accepts both types of tasks.
Although the ScheduledThreadPoolExecutor class is a child class of the ThreadPoolExecutor class and, therefore, inherits all its features, Java recommends the utilization of ScheduledThreadPoolExecutor only for scheduled tasks.
Finally, you can configure the behavior of the ScheduledThreadPoolExecutor class when you call the shutdown() method and there are pending tasks waiting for the end of their delay time. The default behavior is that those tasks will be executed despite the finalization of the executor. You can change this behavior using the setExecuteExistingDelayedTasksAfterShutdownPolicy() method of the ScheduledThreadPoolExecutor class. With false, at the time of shutdown(), pending tasks won't get executed.
Running a task in an executor periodically
The Executor framework provides the ThreadPoolExecutor class to execute concurrent tasks using a pool of threads that avoids you all the thread creation operations. When you send a task to the executor, according to its configuration, it executes the task as soon as possible. When it ends, the task is deleted from the executor and, if you want to execute them again, you have to send it again to the executor.
But the Executor framework provides the possibility of executing periodic tasks through the ScheduledThreadPoolExecutor class. In this case, you will learn how to use this functionality of that class to schedule a periodic task.
/**
* This class implements the task of the example. Writes a message to the
* console with the actual date.
* Is used to explain the utilization of an scheduled executor to execute tasks
* periodically
*/
public class Task implements Runnable { /**
* Name of the task
*/
private String name; /**
* Constructor of the class
* @param name the name of the class
*/
public Task(String name) {
this.name = name;
} /**
* Main method of the example. Writes a message to the console with the actual date
*/
@Override
public void run() {
System.out.printf("%s: Executed at: %s\n", name, new Date());
} } /**
* Main class of the example. Send a task to the executor that will execute every
* two seconds. Then, control the remaining time for the next execution of the task
*/
public class Main { /**
* Main method of the class
* @param args
*/
public static void main(String[] args) { // Create a ScheduledThreadPoolExecutor
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
System.out.printf("Main: Starting at: %s\n",new Date()); // Create a new task and sends it to the executor. It will start with a delay of 1 second
// and then it will execute every two seconds
Task task = new Task("Task");
ScheduledFuture<?> result = executor.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS); // Controlling the execution of tasks
for (int i = 0; i < 10; i++) {
System.out.printf("Main: Delay: %d\n", result.getDelay(TimeUnit.MILLISECONDS));
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} // Finish the executor
executor.shutdown();
System.out.printf("Main: No more tasks at: %s\n", new Date()); // Verify that the periodic tasks no is in execution after the executor shutdown()
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} // The example finish
System.out.printf("Main: Finished at: %s\n",new Date());
}
}
When you want to execute a periodic task using the Executor framework, you need a ScheduledExecutorService object. To create it (as with every executor), Java recommends the use of the Executors class. This class works as a factory of executor objects. In this case, you should use the newScheduledThreadPool() method to create a ScheduledExecutorService object. That method receives as a parameter the number of threads of the pool. As you have only one task in this example, you have passed the value 1 as a parameter.
Once you have the executor needed to execute a periodic task, you send the task to the executor. You have used the scheduledAtFixedRate() method. This method accepts four parameters: the task you want to execute periodically, the delay of time until the first execution of the task, the period between two executions, and the time unit of the second and third parameters. It's a constant of the TimeUnit class. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS.
An important point to consider is that the period between two executions is the period of time between these two executions that begins. If you have a periodic task that takes 5 sceconds to execute and you put a period of 3 seconds, you will have two instances of the task executing at a time.
The method scheduleAtFixedRate() returns a ScheduledFuture object, which extends the Future interface, with methods to work with scheduled tasks. ScheduledFuture is a parameterized interface. In this example, as your task is a Runnable object that is not parameterized, you have to parameterize them with the ? symbol as a parameter.
You have used one method of the ScheduledFuture interface. The getDelay() method returns the time until the next execution of the task. This method receives a TimeUnit constant with the time unit in which you want to receive the results.
The following snippet shows the output of an execution of the example:
Main: Starting at: Mon Nov 07 17:24:22 CST 2016
Main: Delay: 999
Main: Delay: 499
Task: Executed at: Mon Nov 07 17:24:23 CST 2016
Main: Delay: 1998
Main: Delay: 1498
Main: Delay: 998
Main: Delay: 497
Task: Executed at: Mon Nov 07 17:24:25 CST 2016
Main: Delay: 1997
Main: Delay: 1496
Main: Delay: 996
Main: Delay: 496
Task: Executed at: Mon Nov 07 17:24:27 CST 2016
Main: No more tasks at: Mon Nov 07 17:24:27 CST 2016
Main: Finished at: Mon Nov 07 17:24:32 CST 2016
You can see the task executing every 2 seconds (denoted with Task: prefix) and the delay written in the console every 500 milliseconds. That's how long the main thread has been put to sleep. When you shut down the executor, the scheduled task ends its execution and you don't see more messages in the console.
ScheduledThreadPoolExecutor provides other methods to schedule periodic tasks. It is the scheduleWithFixedRate() method. It has the same parameters as the scheduledAtFixedRate() method, but there is a difference worth noticing. In the scheduledAtFixedRate() method, the third parameter determines the period of time between the starting of two executions. In the scheduledWithFixedRate() method, parameter determines the period of time between the end of an execution of the task and the beginning of the next execution.
You can also configure the behavior of an instance of the ScheduledThreadPoolExecutor class with the shutdown() method. The default behavior is that the scheduled tasks finish when you call that method. You can change this behavior using the
setContinueExistingPeriodicTasksAfterShutdownPolicy() method of the ScheduledThreadPoolExecutor class with a true value. The periodic tasks won't finish upon calling the shutdown() method.
Java Concurrency - ScheduledThreadPoolExecutor的更多相关文章
- 深入浅出 Java Concurrency (35): 线程池 part 8 线程池的实现及原理 (3)[转]
线程池任务执行结果 这一节来探讨下线程池中任务执行的结果以及如何阻塞线程.取消任务等等. 1 package info.imxylz.study.concurrency.future;2 3 publ ...
- Java Concurrency in Practice 读书笔记 第十章
粗略看完<Java Concurrency in Practice>这部书,确实是多线程/并发编程的一本好书.里面对各种并发的技术解释得比较透彻,虽然是面向Java的,但很多概念在其他语言 ...
- Java Concurrency - 浅析 CountDownLatch 的用法
The Java concurrency API provides a class that allows one or more threads to wait until a set of ope ...
- Java Concurrency - 浅析 CyclicBarrier 的用法
The Java concurrency API provides a synchronizing utility that allows the synchronization of two or ...
- Java Concurrency - 浅析 Phaser 的用法
One of the most complex and powerful functionalities offered by the Java concurrency API is the abil ...
- Java Concurrency - 线程执行器
Usually, when you develop a simple, concurrent-programming application in Java, you create some Runn ...
- Java Concurrency - Callable & Future
One of the advantages of the Executor framework is that you can run concurrent tasks that return a r ...
- 深入浅出 Java Concurrency (4): 原子操作 part 3 指令重排序与happens-before法则
转: http://www.blogjava.net/xylz/archive/2010/07/03/325168.html 在这个小结里面重点讨论原子操作的原理和设计思想. 由于在下一个章节中会谈到 ...
- 《Java Concurrency》读书笔记,使用JDK并发包构建程序
1. java.util.concurrent概述 JDK5.0以后的版本都引入了高级并发特性,大多数的特性在java.util.concurrent包中,是专门用于多线并发编程的,充分利用了现代多处 ...
随机推荐
- HDU 5835 Danganronpa (水题)
题意:给定 n 个礼物有数量,一种是特殊的,一种是不特殊的,要分给一些人,每人一个特殊的一个不特殊,但是不特殊的不能相邻的,问最多能分给多少人. 析:是一个比较简单的题目,我们只要求差值就好,先算第一 ...
- POJ 3369 Meteor Shower (BFS,水题)
题意:给定 n 个炸弹的坐标和爆炸时间,问你能不能逃出去.如果能输出最短时间. 析:其实这个题并不难,只是当时没读懂,后来读懂后,很容易就AC了. 主要思路是这样的,先标记所有的炸弹的位置,和时间,在 ...
- 校园网通过路由器开WiFi
闲话少说,为了在一个宿舍内达到一个网口N人上网目的,特地写一篇关于校园网通过路由器开wifi的文章,希望能帮助同学把wifi开起来,请看正文(操作以下步骤前建议先重置路由,也就是初始化复位): 一.一 ...
- 【Java】C/C++与Java的简单比较
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5827273.html C/C++: 编译(不同的系统编译出不同的机器码,所以同一 ...
- javascript操作Math对象的方法总结
//数学函数--abs 返回数字的绝对值 var a; /*a = Math.abs(-12); alert(a); //12 //数学函数--acos 返回数的反余弦数 a = Math.acos( ...
- Android访问WebService的两种方法
首先解释一下WebService:WebService是一种基于SOAP协议的远程调用标准.通过WebService可以将不同操作系统平台,不同语言.不同技术整合到一起.详细见:http://baik ...
- Weka – 分类
1. weka简单介绍 1) weka是新西兰怀卡托大学WEKA小组用JAVA开发的机器学习/数据挖掘开源软件. 2) 相关资源链接 http://sourceforge.net/pro ...
- Covarience And ContraVariance
using System; using System.Collections.Generic; using System.IO; namespace CovarientAndContraVarient ...
- Codeforces Gym 100286G Giant Screen 水题
Problem G.Giant ScreenTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/con ...
- delphi array应用 DayOfWeek星期几判断
//array应用 DayOfWeek星期几判断 procedure TForm1.Button1Click(Sender: TObject);var days:array[1..7] of s ...