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包中,是专门用于多线并发编程的,充分利用了现代多处 ...
随机推荐
- SQL语句执行时所发生的步骤
- java 指导 (Java Tutorial)
case1: site:docs.oracle.com -xmx -xms case2: site:docs.oracle.com thread case3: site:docs.oracle.com ...
- string中c_str()、data()、copy(p,n)函数的用法
标准库的string类提供了3个成员函数来从一个string得到c类型的字符数组:c_str().data().copy(p,n). 1. c_str():生成一个const char*指针,指向以空 ...
- 开源原生JavaScript插件-CJPCD(省市区联动)
一.前言 上两篇博客笔者对 JavaScript Module 模式,闭包等知识点做了简单介绍之后,我们今天开始正式开发一款属于自己的 JavaScript 插件.由于最近项目刚好用到地区选择这一块的 ...
- EasyUI 下拉列表联动
//绑定部门.人员下拉菜单项 function BindDdl() { var $ddlbm = $("#ddlBm");//部门下拉列表 var $ddlry = $(" ...
- 检查dns服务器是否可用
#%windir%\system32\WindowsPowerShell\v1.0\powershell.exe D:\PSScript\ERP_Production_Script\ERPRF_Upd ...
- MX记录查询
nslookup set type=mx
- Spring的DataSource配置、将Hibernate配置所有写到Spring配置
DataSource能够集中管理数据库连接,降低维护工作量,使部署更简单: Spring的DataSource配置:(Spring数据源配置)这里使用dbcp,还有非常多其它的如c3p0,jdbc,j ...
- iOS NSString常用用法大全
版权声明:本文为博主Atany原创文章,未经博主允许不得转载.博客地址:http://blog.csdn.net/yang8456211 一.NSRange 在对NSString介绍之前,我们先要了解 ...
- Java中介者设计模式
中介者设计模式是一种很常见的设计模式,当中我们最为熟悉的就是我们的MVC框架.当中的C作为控制器就是一个详细的中介者,它的作用是把业务逻辑(Model),和视图(Viwe)隔离开来.使M V协调工作, ...