1. Общ преглед
ExecutorService е рамка, предоставена от JDK, която опростява изпълнението на задачите в асинхронен режим. Най-общо казано, ExecutorService автоматично предоставя пул от нишки и API за присвояване на задачи към него.
2. Инсталиране на ExecutorService
2.1. Фабрични методи от класа на изпълнителите
Най-лесният начин да създадете ExecutorService е да използвате един от фабричните методи на класа Executors .
Например, следният ред код ще създаде пул от нишки с 10 нишки:
ExecutorService executor = Executors.newFixedThreadPool(10);
Това са няколко други фабрични метода за създаване на предварително дефиниран ExecutorService, които отговарят на конкретни случаи на употреба. За да намерите най-добрия метод за вашите нужди, вижте официалната документация на Oracle.
2.2. Директно създаване на ExecutorService
Тъй като ExecutorService е интерфейс, може да се използва екземпляр на всяка негова реализация. Има няколко реализации, от които можете да избирате в пакета java.util.concurrent или можете да създадете свой собствен.
Например класът ThreadPoolExecutor има няколко конструктора, които могат да бъдат използвани за конфигуриране на услуга изпълнител и нейния вътрешен пул.
ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
Може да забележите, че горният код е много подобен на изходния код на фабричния метод newSingleThreadExecutor (). В повечето случаи не е необходима подробна ръчна конфигурация.
3. Възлагане на задачи на ExecutorService
ExecutorService може да изпълнява Runnable и Callable задачи. За да улеснят нещата в тази статия, ще бъдат използвани две примитивни задачи. Забележете, че тук се използват ламбда изрази вместо анонимни вътрешни класове:
Runnable runnableTask = () -> { try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } }; Callable callableTask = () -> { TimeUnit.MILLISECONDS.sleep(300); return "Task's execution"; }; List
callableTasks = new ArrayList(); callableTasks.add(callableTask); callableTasks.add(callableTask); callableTasks.add(callableTask);
Задачите могат да бъдат възложени на ExecutorService, като се използват няколко метода, включително execute () , който се наследява от интерфейса на Executor , а също и submit () , invokeAny (), invokeAll ().
Методът execute () е невалиден и не дава никаква възможност да се получи резултатът от изпълнението на задачата или да се провери състоянието на задачата (изпълнява ли се или се изпълнява).
executorService.execute(runnableTask);
submit () изпраща Callable или Runnable задача към ExecutorService и връща резултат от тип Future .
Future future = executorService.submit(callableTask);
invokeAny () присвоява колекция от задачи на ExecutorService, причинявайки изпълнението на всяка, и връща резултата от успешно изпълнение на една задача (ако е имало успешно изпълнение) .
String result = executorService.invokeAny(callableTasks);
invokeAll () присвоява колекция от задачи на ExecutorService, причинявайки изпълнението на всяка, и връща резултата от всички изпълнения на задачи под формата на списък с обекти от тип Future .
List
futures = executorService.invokeAll(callableTasks);
Сега, преди да продължите по-нататък, трябва да се обсъдят още две неща: изключване на ExecutorService и справяне с бъдещите типове връщане.
4. Изключване на ExecutorService
По принцип ExecutorService няма да бъде унищожен автоматично, когато няма задача за обработка. Ще остане жив и ще чака нова работа.
В някои случаи това е много полезно; например, ако приложението трябва да обработва задачи, които се появяват нередовно, или количеството на тези задачи не е известно по време на компилиране.
От друга страна, приложението може да достигне своя край, но няма да бъде спряно, защото изчакващата ExecutorService ще накара JVM да продължи да работи.
За да изключим правилно ExecutorService , имаме API на shutdown () и shutdownNow () .
Методът shutdown () не води до незабавно унищожаване на ExecutorService. Това ще накара ExecutorService да спре да приема нови задачи и да се изключи, след като всички работещи нишки приключат текущата си работа.
executorService.shutdown();
Методът shutdownNow () се опитва незабавно да унищожи ExecutorService , но не гарантира, че всички работещи нишки ще бъдат спрени едновременно. Този метод връща списък със задачи, които чакат да бъдат обработени. Разработчикът трябва да реши какво да прави с тези задачи.
List notExecutedTasks = executorService.shutDownNow();
Един добър начин за изключване на ExecutorService (което също се препоръчва от Oracle) е да се използват и двата метода, комбинирани с метода awaitTermination () . С този подход ExecutorService първо ще спре да приема нови задачи, след което ще изчака до определен период от време, за да бъдат изпълнени всички задачи. Ако това време изтече, изпълнението се спира незабавно:
executorService.shutdown(); try { if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); }
5. Бъдещият интерфейс
The submit() and invokeAll() methods return an object or a collection of objects of type Future, which allows us to get the result of a task's execution or to check the task's status (is it running or executed).
The Future interface provides a special blocking method get() which returns an actual result of the Callable task's execution or null in the case of Runnable task. Calling the get() method while the task is still running will cause execution to block until the task is properly executed and the result is available.
Future future = executorService.submit(callableTask); String result = null; try { result = future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); }
With very long blocking caused by the get() method, an application's performance can degrade. If the resulting data is not crucial, it is possible to avoid such a problem by using timeouts:
String result = future.get(200, TimeUnit.MILLISECONDS);
If the execution period is longer than specified (in this case 200 milliseconds), a TimeoutException will be thrown.
The isDone() method can be used to check if the assigned task is already processed or not.
The Future interface also provides for the cancellation of task execution with the cancel() method, and to check the cancellation with isCancelled() method:
boolean canceled = future.cancel(true); boolean isCancelled = future.isCancelled();
6. The ScheduledExecutorService Interface
The ScheduledExecutorService runs tasks after some predefined delay and/or periodically. Once again, the best way to instantiate a ScheduledExecutorService is to use the factory methods of the Executors class.
For this section, a ScheduledExecutorService with one thread will be used:
ScheduledExecutorService executorService = Executors .newSingleThreadScheduledExecutor();
To schedule a single task's execution after a fixed delay, us the scheduled() method of the ScheduledExecutorService. There are two scheduled() methods that allow you to execute Runnable or Callable tasks:
Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
The scheduleAtFixedRate() method lets execute a task periodically after a fixed delay. The code above delays for one second before executing callableTask.
The following block of code will execute a task after an initial delay of 100 milliseconds, and after that, it will execute the same task every 450 milliseconds. If the processor needs more time to execute an assigned task than the period parameter of the scheduleAtFixedRate() method, the ScheduledExecutorService will wait until the current task is completed before starting the next:
Future resultFuture = service .scheduleAtFixedRate(runnableTask, 100, 450, TimeUnit.MILLISECONDS);
If it is necessary to have a fixed length delay between iterations of the task, scheduleWithFixedDelay() should be used. For example, the following code will guarantee a 150-millisecond pause between the end of the current execution and the start of another one.
service.scheduleWithFixedDelay(task, 100, 150, TimeUnit.MILLISECONDS);
According to the scheduleAtFixedRate() and scheduleWithFixedDelay() method contracts, period execution of the task will end at the termination of the ExecutorService or if an exception is thrown during task execution.
7. ExecutorService vs. Fork/Join
After the release of Java 7, many developers decided that the ExecutorService framework should be replaced by the fork/join framework. This is not always the right decision, however. Despite the simplicity of usage and the frequent performance gains associated with fork/join, there is also a reduction in the amount of developer control over concurrent execution.
ExecutorService gives the developer the ability to control the number of generated threads and the granularity of tasks which should be executed by separate threads. The best use case for ExecutorService is the processing of independent tasks, such as transactions or requests according to the scheme “one thread for one task.”
In contrast, according to Oracle's documentation, fork/join was designed to speed up work which can be broken into smaller pieces recursively.
8. Conclusion
Even despite the relative simplicity of ExecutorService, there are a few common pitfalls. Let's summarize them:
Keeping an unused ExecutorService alive: There is a detailed explanation in section 4 of this article about how to shut down an ExecutorService;
Wrong thread-pool capacity while using fixed length thread-pool: It is very important to determine how many threads the application will need to execute tasks efficiently. A thread-pool that is too large will cause unnecessary overhead just to create threads which mostly will be in the waiting mode. Too few can make an application seem unresponsive because of long waiting periods for tasks in the queue;
Calling a Future‘s get() method after task cancellation: An attempt to get the result of an already canceled task will trigger a CancellationException.
Unexpectedly-long blocking with Future‘s get() method: Timeouts should be used to avoid unexpected waits.
Кодът за тази статия е достъпен в хранилище на GitHub.