1. Introducción
En este artículo, veremos uno de los mecanismos más fundamentales en Java: la sincronización de subprocesos.
Primero discutiremos algunos términos y metodologías esenciales relacionados con la concurrencia.
Y desarrollaremos una aplicación simple, donde nos ocuparemos de los problemas de concurrencia, con el objetivo de comprender mejor wait () y notificar ().
2. Sincronización de subprocesos en Java
En un entorno multiproceso, varios subprocesos pueden intentar modificar el mismo recurso. Si los hilos no se administran correctamente, esto, por supuesto, dará lugar a problemas de coherencia.
2.1. Bloques protegidos en Java
Una herramienta que podemos usar para coordinar acciones de múltiples subprocesos en Java son los bloques protegidos. Dichos bloques mantienen una verificación de una condición particular antes de reanudar la ejecución.
Con eso en mente, haremos uso de:
- Object.wait () - para suspender un hilo
- Object.notify () - para despertar un hilo
Esto se puede entender mejor en el siguiente diagrama, que muestra el ciclo de vida de un hilo :

Tenga en cuenta que hay muchas formas de controlar este ciclo de vida; sin embargo, en este artículo, nos centraremos solo en esperar () y notificar ().
3. El método wait ()
En pocas palabras, cuando llamamos a wait (), esto obliga al subproceso actual a esperar hasta que otro subproceso invoca notificar () o notificar a todos () en el mismo objeto.
Para ello, el hilo actual debe ser propietario del monitor del objeto. Según Javadocs, esto puede suceder cuando:
- hemos ejecutado un método de instancia sincronizado para el objeto dado
- hemos ejecutado el cuerpo de un bloque sincronizado en el objeto dado
- ejecutando métodos estáticos sincronizados para objetos de tipo Class
Tenga en cuenta que solo un subproceso activo puede poseer el monitor de un objeto a la vez.
Este método wait () viene con tres firmas sobrecargadas. Echemos un vistazo a estos.
3.1. Espere()
El método wait () hace que el subproceso actual espere indefinidamente hasta que otro subproceso invoca a notify () para este objeto o notifyAll () .
3.2. espera (tiempo de espera largo)
Con este método, podemos especificar un tiempo de espera después del cual el hilo se activará automáticamente. Un hilo se puede despertar antes de alcanzar el tiempo de espera usando notificar () o notificar a todos ().
Tenga en cuenta que llamar a wait (0) es lo mismo que llamar a wait ().
3.3. espera (tiempo de espera largo, nanos int)
Esta es otra firma que proporciona la misma funcionalidad, con la única diferencia de que podemos proporcionar una mayor precisión.
El período de tiempo de espera total (en nanosegundos) se calcula como 1_000_000 * tiempo de espera + nanos.
4. notificar () y notificar a todos ()
El método notificar () se usa para despertar los hilos que están esperando un acceso al monitor de este objeto.
Hay dos formas de notificar los hilos en espera.
4.1. notificar()
Para todos los subprocesos que esperan en el monitor de este objeto (mediante el uso de cualquiera de los métodos wait () ), el método notificar () notifica a cualquiera de ellos que se despierte arbitrariamente. La elección de exactamente qué hilo despertar no es determinista y depende de la implementación.
Dado que notify () despierta un solo subproceso aleatorio, se puede usar para implementar un bloqueo mutuamente excluyente donde los subprocesos realizan tareas similares, pero en la mayoría de los casos, sería más viable implementar notifyAll () .
4.2. notificar a todos ()
Este método simplemente despierta todos los subprocesos que están esperando en el monitor de este objeto.
Los hilos despertados se completarán de la manera habitual, como cualquier otro hilo.
Pero antes de permitir que continúe su ejecución, siempre defina una verificación rápida de la condición requerida para continuar con el hilo , porque puede haber algunas situaciones en las que el hilo se despertó sin recibir una notificación (este escenario se analiza más adelante en un ejemplo) .
5. Problema de sincronización de remitente-receptor
Ahora que entendemos los conceptos básicos, veamos una sencilla aplicación Remitente - Receptor - que hará uso de los métodos wait () y notificar () para configurar la sincronización entre ellos:
- Se supone que el remitente debe enviar un paquete de datos al receptor
- El receptor no puede procesar el paquete de datos hasta que el remitente haya terminado de enviarlo
- Del mismo modo, el remitente no debe intentar enviar otro paquete a menos que el receptor ya haya procesado el paquete anterior.
Let's first create Data class that consists of the data packet that will be sent from Sender to Receiver. We'll use wait() and notifyAll() to set up synchronization between them:
public class Data { private String packet; // True if receiver should wait // False if sender should wait private boolean transfer = true; public synchronized void send(String packet) { while (!transfer) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } transfer = false; this.packet = packet; notifyAll(); } public synchronized String receive() { while (transfer) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } transfer = true; notifyAll(); return packet; } }
Let's break down what's going on here:
- The packet variable denotes the data that is being transferred over the network
- We have a boolean variable transfer – which the Sender and Receiver will use for synchronization:
- If this variable is true, then the Receiver should wait for Sender to send the message
- If it's false, then Sender should wait for Receiver to receive the message
- The Sender uses send() method to send data to the Receiver:
- If transfer is false, we'll wait by calling wait() on this thread
- But when it is true, we toggle the status, set our message and call notifyAll() to wake up other threads to specify that a significant event has occurred and they can check if they can continue execution
- Similarly, the Receiver will use receive() method:
- If the transfer was set to false by Sender, then only it will proceed, otherwise we'll call wait() on this thread
- When the condition is met, we toggle the status, notify all waiting threads to wake up and return the data packet that was Receiver
5.1. Why Enclose wait() in a while Loop?
Since notify() and notifyAll() randomly wakes up threads that are waiting on this object's monitor, it's not always important that the condition is met. Sometimes it can happen that the thread is woken up, but the condition isn't actually satisfied yet.
We can also define a check to save us from spurious wakeups – where a thread can wake up from waiting without ever having received a notification.
5.2. Why Do We Need to Synchronize send() and receive() Methods?
We placed these methods inside synchronized methods to provide intrinsic locks. If a thread calling wait() method does not own the inherent lock, an error will be thrown.
We'll now create Sender and Receiver and implement the Runnable interface on both so that their instances can be executed by a thread.
Let's first see how Sender will work:
public class Sender implements Runnable { private Data data; // standard constructors public void run() { String packets[] = { "First packet", "Second packet", "Third packet", "Fourth packet", "End" }; for (String packet : packets) { data.send(packet); // Thread.sleep() to mimic heavy server-side processing try { Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } } }
For this Sender:
- We're creating some random data packets that will be sent across the network in packets[] array
- For each packet, we're merely calling send()
- Then we're calling Thread.sleep() with random interval to mimic heavy server-side processing
Finally, let's implement our Receiver:
public class Receiver implements Runnable { private Data load; // standard constructors public void run() { for(String receivedMessage = load.receive(); !"End".equals(receivedMessage); receivedMessage = load.receive()) { System.out.println(receivedMessage); // ... try { Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } } }
Here, we're simply calling load.receive() in the loop until we get the last “End” data packet.
Let's now see this application in action:
public static void main(String[] args) { Data data = new Data(); Thread sender = new Thread(new Sender(data)); Thread receiver = new Thread(new Receiver(data)); sender.start(); receiver.start(); }
We'll receive the following output:
First packet Second packet Third packet Fourth packet
And here we are – we've received all data packets in the right, sequential order and successfully established the correct communication between our sender and receiver.
6. Conclusion
In this article, we discussed some core synchronization concepts in Java; more specifically, we focused on how we can use wait() and notify() to solve interesting synchronization problems. And finally, we went through a code sample where we applied these concepts in practice.
Before we wind down here, it's worth mentioning that all these low-level APIs, such as wait(), notify() and notifyAll() – are traditional methods that work well, but higher-level mechanism are often simpler and better – such as Java's native Lock and Condition interfaces (available in java.util.concurrent.locks package).
Para obtener más información sobre el paquete java.util.concurrent , visite nuestra descripción general del artículo java.util.concurrent, y el bloqueo y la condición se tratan en la guía de java.util.concurrent.Locks, aquí.
Como siempre, los fragmentos de código completos que se usan en este artículo están disponibles en GitHub.