Una guía para Java ExecutorService

1. Información general

ExecutorService es un marco proporcionado por el JDK que simplifica la ejecución de tareas en modo asíncrono. En términos generales, ExecutorService proporciona automáticamente un grupo de subprocesos y API para asignarle tareas.

2. Creación de instancias de ExecutorService

2.1. Métodos de fábrica de la clase Ejecutores

La forma más sencilla de crear ExecutorService es utilizar uno de los métodos de fábrica de la clase Executors .

Por ejemplo, la siguiente línea de código creará un grupo de subprocesos con 10 subprocesos:

ExecutorService executor = Executors.newFixedThreadPool(10);

Hay varios otros métodos de fábrica para crear ExecutorService predefinidos que cumplen con casos de uso específicos. Para encontrar el mejor método para sus necesidades, consulte la documentación oficial de Oracle.

2.2. Crear directamente un ExecutorService

Como ExecutorService es una interfaz, se puede utilizar una instancia de cualquiera de sus implementaciones. Hay varias implementaciones para elegir en el paquete java.util.concurrent o puede crear la suya propia.

Por ejemplo, la clase ThreadPoolExecutor tiene algunos constructores que pueden usarse para configurar un servicio ejecutor y su grupo interno.

ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());

Puede notar que el código anterior es muy similar al código fuente del método de fábrica newSingleThreadExecutor (). En la mayoría de los casos, no es necesaria una configuración manual detallada.

3. Asignación de tareas al ExecutorService

ExecutorService puede ejecutar tareas ejecutables y invocables . Para simplificar las cosas en este artículo, se utilizarán dos tareas primitivas. Observe que aquí se usan expresiones lambda en lugar de clases internas anónimas:

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);
    

Las tareas se pueden asignar al ExecutorService utilizando varios métodos, incluido execute () , que se hereda de la interfaz Executor , y también submit () , invokeAny (), invokeAll ().

El método execute () es nulo y no ofrece ninguna posibilidad de obtener el resultado de la ejecución de la tarea o de verificar el estado de la tarea (si se está ejecutando o se está ejecutando).

executorService.execute(runnableTask);

submit () envía una tarea invocable o ejecutable a ExecutorService y devuelve un resultado de tipo Future .

Future future = executorService.submit(callableTask);

invokeAny () asigna una colección de tareas a un ExecutorService, haciendo que cada una se ejecute, y devuelve el resultado de una ejecución exitosa de una tarea (si hubo una ejecución exitosa) .

String result = executorService.invokeAny(callableTasks);

invokeAll () asigna una colección de tareas a un ExecutorService, haciendo que cada una se ejecute, y devuelve el resultado de todas las ejecuciones de tareas en forma de una lista de objetos de tipo Future .

List
    
      futures = executorService.invokeAll(callableTasks);
    

Ahora, antes de continuar, se deben discutir dos cosas más: cerrar un ExecutorService y lidiar con los tipos de retorno futuros .

4. Cerrar un ExecutorService

En general, ExecutorService no se destruirá automáticamente cuando no haya ninguna tarea que procesar. Se mantendrá vivo y esperará a que se realice un nuevo trabajo.

En algunos casos esto es muy útil; por ejemplo, si una aplicación necesita procesar tareas que aparecen de forma irregular o la cantidad de estas tareas no se conoce en el momento de la compilación.

Por otro lado, una aplicación podría llegar a su fin, pero no se detendrá porque un ExecutorService en espera hará que la JVM siga ejecutándose.

Para cerrar correctamente un ExecutorService , tenemos las API shutdown () y shutdownNow () .

El método shutdown () no causa la destrucción inmediata del ExecutorService. Hará que ExecutorService deje de aceptar nuevas tareas y se apague después de que todos los subprocesos en ejecución terminen su trabajo actual.

executorService.shutdown();

El método shutdownNow () intenta destruir ExecutorService inmediatamente, pero no garantiza que todos los subprocesos en ejecución se detendrán al mismo tiempo. Este método devuelve una lista de tareas que están esperando ser procesadas. Depende del desarrollador decidir qué hacer con estas tareas.

List notExecutedTasks = executorService.shutDownNow();

Una buena forma de cerrar ExecutorService (que también es recomendado por Oracle) es usar ambos métodos combinados con el método awaitTermination () . Con este enfoque, ExecutorService primero dejará de tomar nuevas tareas y luego esperará hasta un período de tiempo específico para que se completen todas las tareas. Si ese tiempo expira, la ejecución se detiene inmediatamente:

executorService.shutdown(); try { if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); }

5. La interfaz del futuro

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.

El código de este artículo está disponible en un repositorio de GitHub.