Preface
The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool. In fact, the implementation of ExecutorService present in the java.util.concurrent package is a thread pool implementation. (Youtube tutorial link)
ExecutorService Example
Here is a simple Java ExectorService example:
- ExecutorService executorService = Executors.newFixedThreadPool(10);
- executorService.execute(new Runnable() {
- public void run() {
- System.out.println("Asynchronous task");
- }
- });
- executorService.shutdown();
Task Delegation
Here is a diagram illustrating a thread delegating a task to an ExecutorService for asynchronous execution:
Once the thread has delegated the task to the ExecutorService, the thread continues its own execution independent of the execution of that task.
ExecutorService Implementations
Since ExecutorService is an interface, you need to understand its implementations in order to make any use of it. The ExecutorService has the following implementation in the java.util.concurrent package:
* ThreadPoolExecutor
* ScheduledThreadPoolExecutor
Creating an ExecutorService
How you create an ExecutorService depends on the implementation you use. However, you can use the Executors factory class to create ExecutorServiceinstances too. Here are a few examples of creating an ExecutorService:
- # Creates an Executor that uses a single worker thread operating off an unbounded queue.
- ExecutorService executorService1 = Executors.newSingleThreadExecutor();
- # Creates a thread pool that reuses a fixed number of threads as 10 operating off a shared unbounded queue.
- ExecutorService executorService2 = Executors.newFixedThreadPool(10);
- # Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically. (10 fixed threads here)
- ExecutorService executorService3 = Executors.newScheduledThreadPool(10);
There are a few different ways to delegate tasks for execution to an ExecutorService:
I will take a look at each of these methods in the following sections.
execute(Runnable)
The execute(Runnable) method takes a java.lang.Runnable object, and executes it asynchronously. Here is an example of executing a Runnable with anExecutorService:
- ExecutorService executorService = Executors.newSingleThreadExecutor();
- executorService.execute(new Runnable() {
- public void run() {
- System.out.println("Asynchronous task");
- }
- });
- executorService.shutdown();
submit(Runnable)
The submit(Runnable) method also takes a Runnable implementation, but returns a Future object. This Future object can be used to check if the Runnable as finished executing. Here is a ExecutorService submit() example:
- Future future = executorService.submit(new Runnable() {
- public void run() {
- System.out.println("Asynchronous task");
- }
- });
- future.get(); //returns null if the task has finished correctly.
The submit(Callable) method is similar to the submit(Runnable) method except for the type of parameter it takes. The Callable instance is very similar to aRunnable except that its call() method can return a result. The Runnable.run() method cannot return a result.
The Callable's result can be obtained via the Future object returned by the submit(Callable) method. Here is an ExecutorService Callable example:
- Future future = executorService.submit(new Callable(){
- public Object call() throws Exception {
- System.out.println("Asynchronous Callable");
- return "Callable Result";
- }
- });
- System.out.println("future.get() = " + future.get());
The invokeAny() method takes a collection of Callable objects, or subinterfaces of Callable. Invoking this method does not return a Future, but returns the result of one of the Callable objects. You have no guarantee about which of the Callable's results you get. Just one of the ones that finish.
If one of the tasks complete (or throws an exception), the rest of the Callable's are cancelled. Here is a code example:
- ExecutorService executorService = Executors.newFixedThreadPool(3);
- Set
> callables = new HashSet >(); - callables.add(new Callable
() { - public String call() throws Exception {
- sleep 1000
- return "Task 1";
- }
- });
- callables.add(new Callable
() { - public String call() throws Exception {
- sleep 3000
- return "Task 2";
- }
- });
- callables.add(new Callable
() { - public String call() throws Exception {
- sleep 100
- return "Task 3";
- }
- });
- printf("Blocking...\n")
- String result = executorService.invokeAny(callables);
- printf("Done!\n")
- System.out.println("result = " + result);
- // Wait for all tasks to be done!
- executorService.shutdown();
- printf("Exit main thread!")
invokeAll()
The invokeAll() method invokes all of the Callable objects you pass to it in the collection passed as parameter. The invokeAll() returns a list of Future objects via which you can obtain the results of the executions of each Callable. Keep in mind that a task might finish due to an exception, so it may not have "succeeded". There is no way on a Future to tell the difference.
Here is a code example:
- import java.util.concurrent.Callable
- import java.util.concurrent.ExecutorService
- import java.util.concurrent.Executors
- import java.util.concurrent.Future
- import flib.util.TimeStr
- ExecutorService executorService = Executors.newSingleThreadExecutor();
- Set
> callables = new HashSet >(); - long st = System.currentTimeMillis()
- callables.add(new Callable
() { - public String call() throws Exception {
- sleep 3000
- return "Task 1";
- }
- });
- callables.add(new Callable
() { - public String call() throws Exception {
- sleep 2000
- return "Task 2";
- }
- });
- callables.add(new Callable
() { - public String call() throws Exception {
- sleep 1000
- return "Task 3";
- }
- });
- printf("\t[Info] invokeAll...(%s)\n", TimeStr.ToStringFrom(st))
- List
> futures = executorService.invokeAll(callables); - printf("\t[Info] Iterate futures(%s):\n", , TimeStr.ToStringFrom(st))
- for(Future
future : futures){ - System.out.println("\tfuture.get = " + future.get());
- }
- printf("\t[Info] Shutdown executor service...(%s)\n", TimeStr.ToStringFrom(st))
- executorService.shutdown();
- printf("\t[Info] Exit main thread...(%s)\n", TimeStr.ToStringFrom(st))
s are done!
future.get = Task 3
future.get = Task 2
future.get = Task 1
[Info] Shutdown executor service...(6 sec)
[Info] Exit main thread...(6 sec)
ExecutorService Shutdown
When you are done using the ExecutorService you should shut it down, so the threads do not keep running.
For instance, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an activeExexutorService in your application. The active threads inside this ExexutorService prevents the JVM from shutting down.
To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService beforeshutdown() is called, are executed. Below is sample code for demonstration:
- import java.util.concurrent.Callable
- import java.util.concurrent.ExecutorService
- import java.util.concurrent.Executors
- import java.util.concurrent.Future
- import flib.util.TimeStr
- ExecutorService executorService = Executors.newSingleThreadExecutor();
- Set
> callables = new HashSet >(); - long st = System.currentTimeMillis()
- Callable
longJob = new Callable () { - public String call() throws Exception {
- sleep 10000
- printf("\t[Info] Long job done! (%s)\n", TimeStr.toStringFrom(st))
- return "Task 1";
- }
- }
- printf("\t[Info] Submit long job...(%s)\n", TimeStr.toStringFrom(st))
- Future future = executorService.submit(longJob)
- printf("\t[Info] Wait 2 sec for job done...(%s)\n", TimeStr.toStringFrom(st))
- sleep 2000
- printf("\t[Info] Can't wait it anymore ><\"...(%s)\n", TimeStr.toStringFrom(st))
- printf("\t[Info] Plan to shutdown executor...(%s)\n", TimeStr.toStringFrom(st))
- executorService.shutdown()
- printf("\t[Info] Shutdown executor done...(%s)\n", TimeStr.toStringFrom(st))
- printf("\t[Info] ...\n")
- sleep 2000
- printf("\t[Info] Can't terminate JVM...Try to cancel future object...(%s)\n", TimeStr.toStringFrom(st))
- future.cancel(true)
- printf("\t[Info] Cancel future done!...(%s)\n", TimeStr.toStringFrom(st))
If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.
Supplement
* ThreadPoolExecutor usage tutorial
沒有留言:
張貼留言