Alta Concurrencia

When facing high concurrency applications, we often find a number of generic problems. In this article I will focus on the problems of resources (CPU and memory). For now on, I will focus on the most typical and most direct solutions.

When we discover threads and the advantages of parallel processing it can happen that we end up abusing their use. We have a lot of threads (100 ¿? 1000?) simultaneously, and the processor will be jumping from one to another without stopping, not letting them finish, no matter how fast is their real excution. And over time there will be more and more threads only slowing down the process. To the cost of execution of each thread, we must consider also the added cost of creating and destroying threads. It can can become significant when we talk about so many threads at once.

High Concurrency with the Thread Pool Pattern
High Concurrency with the Thread Pool Pattern

Threads: the holy grail

En este caso, al primer método al que debemos recurrir es al Patrón Thread Pool . Este patrón consiste en limitar el número de hilos que hay ejecutándose en un momento dado.
En vez de crear hilos nuevos, creamos tareas, que esperan apiladas. Así mismo, tendremos un pool de hilos que irán cogiendo esas tareas y ejecutándolas lo más pronto posible. Un ejemplo clásico de este patrón se encuentra en la clase SwingWorker. Si queremos implementar "a mano" este patrón, conviene que le echemos un vistazo a la interfaz ExecutorService.

Si tenemos un hilo en background que está haciendo un uso muy intensivo del procesador, pero no nos importa ralentizar su ejecución, podemos hacer uso del comando sleep ( Thread.sleep (...)) to periodically release the thread processor, allowing other threads to run faster .

This is useful for threads running in maintenance mode, which must be kept running but do not have to respond in real time. Another way to temporarily stop a running thread while another is using the method join ( Thread.Join () ), que hace que un hilo espere hasta que el otro hilo termine. Aunque más útil en caso de que tengamos un hilo claramente más prioritario que otro, no es viable si no podemos tener una referencia al hilo más prioritario desde el menos prioritario para indicarle a qué hilo tiene que esperar.

High Concurrency issues

Pero la alta concurrencia no viene dada sólo por el uso del procesador. Puede ocurrir que varios hilos necesiten acceder a grandes cantidades de información de forma casi simultánea. Estos hilos no sólo estarán repitiendo la información en memoria sino que muchas veces estarán repitiendo todo el proceso de extraer dicha información.

Este problema suele estar resuelto en la mayoría de librerías de acceso a datos (base de datos mayormente). Por ejemplo, podemos encontrarnos con el caso de ehcache , que utiliza hilos para almacenar información ( Thread-Specific Storage Pattern ). This way, access and storage of this information is shared. Thus decreasing both the memory usage required and the processor time required to extract and shape information. As the threads wants to process this information, they will be asking ehcache for the data, which will optimize these hits.

Para mejorar esta solución tenemos las colecciones concurrentes. This allow different threads to use the same objects without any problems of concurrency.

There are more solutions to improve the high turnout (without going into optimizations to the code itself). But those described here are usually good ideas to start.

Referencias Útiles:

Autor: María Arias de Reyna Domínguez

Redhatter, Feminist, Geoinquieta, Atheist, crazy of the pussy and Social Justice Warrior. Chaotic good.

Un comentario en “High Concurrency”

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

es_ESEspañol