1. Introducción
En este tutorial, aprenderemos qué son las estructuras de datos sin bloqueo y por qué son una alternativa importante a las estructuras de datos concurrentes basadas en bloqueos.
En primer lugar, vamos a repasar algunos términos como obstrucción libre , bloqueo libre y sin espera .
En segundo lugar, veremos los bloques de construcción básicos de algoritmos sin bloqueo como CAS (comparar e intercambiar).
En tercer lugar, veremos la implementación de una cola sin bloqueos en Java y, finalmente, describiremos un enfoque sobre cómo lograr la libertad de espera .
2. Bloqueo versus hambre
Primero, veamos la diferencia entre un hilo bloqueado y uno hambriento.

En la imagen de arriba, Thread 2 adquiere un bloqueo en la estructura de datos. Cuando el hilo 1 también intenta adquirir un bloqueo, debe esperar hasta que el hilo 2 lo libere; no procederá antes de que pueda obtener el bloqueo. Si suspendemos el hilo 2 mientras mantiene el bloqueo, el hilo 1 tendrá que esperar una eternidad.
La siguiente imagen ilustra la falta de hilo:

Aquí, Thread 2 accede a la estructura de datos pero no adquiere un bloqueo. El hilo 1 intenta acceder a la estructura de datos al mismo tiempo, detecta el acceso concurrente y regresa inmediatamente, informando al hilo que no pudo completar (rojo) la operación. El hilo 1 volverá a intentarlo hasta que complete la operación (verde).
La ventaja de este enfoque es que no necesitamos un candado. Sin embargo, lo que puede suceder es que si Thread 2 (u otros hilos) acceden a la estructura de datos con alta frecuencia, entonces Thread 1 necesita una gran cantidad de intentos hasta que finalmente tenga éxito. A esto lo llamamos hambre.
Más adelante veremos cómo la operación de comparar e intercambiar logra un acceso sin bloqueo.
3. Tipos de estructuras de datos sin bloqueo
Podemos distinguir entre tres niveles de estructuras de datos sin bloqueo.
3.1. Libre de obstrucciones
La libertad de obstrucción es la forma más débil de una estructura de datos sin bloqueo. Aquí, solo requerimos que un hilo esté garantizado para continuar si todos los demás hilos están suspendidos .
Más precisamente, un hilo no seguirá muriendo de hambre si todos los demás hilos están suspendidos. Esto es diferente de usar bloqueos en ese sentido, que si el hilo estaba esperando un bloqueo y un hilo que retiene el bloqueo está suspendido, el hilo en espera esperaría para siempre.
3.2. Sin bloqueo
Una estructura de datos proporciona libertad de bloqueo si, en cualquier momento, al menos un hilo puede continuar . Todos los demás hilos pueden estar muriendo de hambre. La diferencia con la libertad de obstrucción es que hay al menos un hilo que no muere de hambre incluso si no hay hilos suspendidos.
3.3. Sin espera
Una estructura de datos está libre de espera si está libre de bloqueos y se garantiza que cada subproceso continuará después de un número finito de pasos, es decir, los subprocesos no se morirán de hambre por un número "irrazonablemente grande" de pasos.
3.4. Resumen
Resumamos estas definiciones en representación gráfica:

La primera parte de la imagen muestra la ausencia de obstrucciones ya que el hilo 1 (hilo superior) puede continuar (flecha verde) tan pronto como suspendamos los otros hilos (en la parte inferior en amarillo).
La parte central muestra libertad de bloqueo. Al menos el hilo 1 puede progresar mientras que otros pueden estar muriendo de hambre (flecha roja).
La última parte muestra la libertad de espera. Aquí, garantizamos que el hilo 1 puede continuar (flecha verde) después de un cierto período de inanición (flechas rojas).
4. Primitivas no bloqueantes
En esta sección, veremos tres operaciones básicas que nos ayudan a construir operaciones sin bloqueos en estructuras de datos.
4.1. Comparar e intercambiar
Una de las operaciones básicas que se utilizan para evitar el bloqueo es la operación de comparación e intercambio (CAS) .
La idea de comparar e intercambiar es que una variable solo se actualiza si todavía tiene el mismo valor que en el momento en que obtuvimos el valor de la variable de la memoria principal. CAS es una operación atómica, lo que significa que buscar y actualizar juntas son una sola operación :

Aquí, ambos subprocesos obtienen el valor 3 de la memoria principal. El subproceso 2 tiene éxito (verde) y actualiza la variable a 8. Como el primer CAS del subproceso 1 espera que el valor siga siendo 3, el CAS falla (rojo). Por lo tanto, el subproceso 1 recupera el valor nuevamente y el segundo CAS tiene éxito.
Lo importante aquí es que CAS no adquiere un bloqueo en la estructura de datos, pero devuelve verdadero si la actualización fue exitosa, de lo contrario devuelve falso .
El siguiente fragmento de código describe cómo funciona CAS:
volatile int value; boolean cas(int expectedValue, int newValue) { if(value == expectedValue) { value = newValue; return true; } return false; }
We only update the value with the new value if it still has the expected value, otherwise, it returns false. The following code snippet shows how CAS can be called:
void testCas() { int v = value; int x = v + 1; while(!cas(v, x)) { v = value; x = v + 1; } }
We attempt to update our value until the CAS operation succeeds, that is, returns true.
However, it's possible that a thread gets stuck in starvation. That can happen if other threads perform a CAS on the same variable at the same time, so the operation will never succeed for a particular thread (or will take an unreasonable amount of time to succeed). Still, if the compare-and-swap fails, we know that another thread has succeeded, thus we also ensure global progress, as required for lock-freedom.
It's important to note that the hardware should support compare-and-swap, to make it a truly atomic operation without the use of locking.
Java provides an implementation of compare-and-swap in the class sun.misc.Unsafe. However, in most cases, we should not use this class directly, but Atomic variables instead.
Furthermore, compare-and-swap does not prevent the A-B-A problem. We'll look at that in the following section.
4.2. Load-Link/Store-Conditional
An alternative to compare-and-swap is load-link/store-conditional. Let's first revisit compare-and-swap. As we've seen before, CAS only updates the value if the value in the main memory is still the value we expect it to be.
However, CAS also succeeds if the value had changed, and, in the meantime, has changed back to its previous value.
The below image illustrates this situation:

Both, thread 1 and Thread 2 read the value of the variable, which is 3. Then Thread 2 performs a CAS, which succeeds in setting the variable to 8. Then again, Thread 2 performs a CAS to set the variable back to 3, which succeeds as well. Finally, Thread 1 performs a CAS, expecting the value 3, and succeeds as well, even though the value of our variable was modified twice in between.
This is called the A-B-A problem. This behavior might not be a problem depending on the use-case, of course. However, it might not be desired for others. Java provides an implementation of load-link/store-conditional with the AtomicStampedReference class.
4.3. Fetch and Add
Another alternative is fetch-and-add. This operation increments the variable in the main memory by a given value. Again, the important point is that the operation happens atomically, which means no other thread can interfere.
Java provides an implementation of fetch-and-add in its atomic classes. Examples are AtomicInteger.incrementAndGet(), which increments the value and returns the new value; and AtomicInteger.getAndIncrement(), which returns the old value and then increments the value.
5. Accessing a Linked Queue from Multiple Threads
To better understand the problem of two (or more) threads accessing a queue simultaneously, let's look at a linked queue and two threads trying to add an element concurrently.
The queue we'll look at is a doubly-linked FIFO queue where we add new elements after the last element (L) and the variable tail points to that last element:

To add a new element, the threads need to perform three steps: 1) create the new elements (N and M), with the pointer to the next element set to null; 2) have the reference to the previous element point to L and the reference to the next element of L point to N (M, respectively). 3) Have tail point to N (M, respectively):

What can go wrong if the two threads perform these steps simultaneously? If the steps in the above picture execute in the order ABCD or ACBD, L, as well as tail, will point to M. N will remain disconnected from the queue.
If the steps execute in the order ACDB, tail will point to N, while L will point to M, which will cause an inconsistency in the queue:

Of course, one way to solve this problem is to have one thread acquire a lock on the queue. The solution we'll look at in the following chapter will solve the problem with the help of a lock-free operation by using the CAS operation we've seen earlier.
6. A Non-Blocking Queue in Java
Let's look at a basic lock-free queue in Java. First, let's look at the class members and the constructor:
public class NonBlockingQueue { private final AtomicReference
head, tail; private final AtomicInteger size; public NonBlockingQueue() { head = new AtomicReference(null); tail = new AtomicReference(null); size = new AtomicInteger(); size.set(0); } }
The important part is the declaration of the head and tail references as AtomicReferences, which ensures that any update on these references is an atomic operation. This data type in Java implements the necessary compare-and-swap operation.
Next, let's look at the implementation of the Node class:
private class Node { private volatile T value; private volatile Node next; private volatile Node previous; public Node(T value) { this.value = value; this.next = null; } // getters and setters }
Here, the important part is to declare the references to the previous and next node as volatile. This ensures that we update these references always in the main memory (thus are directly visible to all threads). The same for the actual node value.
6.1. Lock-Free add
Our lock-free add operation will make sure that we add the new element at the tail and won't be disconnected from the queue, even if multiple threads want to add a new element concurrently:
public void add(T element) { if (element == null) { throw new NullPointerException(); } Node node = new Node(element); Node currentTail; do { currentTail = tail.get(); node.setPrevious(currentTail); } while(!tail.compareAndSet(currentTail, node)); if(node.previous != null) { node.previous.next = node; } head.compareAndSet(null, node); // for inserting the first element size.incrementAndGet(); }
The essential part to pay attention to is the highlighted line. We attempt to add the new node to the queue until the CAS operation succeeds to update the tail, which must still be the same tail to which we appended the new node.
6.2. Lock-Free get
Similar to the add-operation, the lock-free get-operation will make sure that we return the last element and move the tail to the current position:
public T get() { if(head.get() == null) { throw new NoSuchElementException(); } Node currentHead; Node nextNode; do { currentHead = head.get(); nextNode = currentHead.getNext(); } while(!head.compareAndSet(currentHead, nextNode)); size.decrementAndGet(); return currentHead.getValue(); }
Again, the essential part to pay attention to is the highlighted line. The CAS operation ensures that we move the current head only if no other node has been removed in the meantime.
Java already provides an implementation of a non-blocking queue, the ConcurrentLinkedQueue. It's an implementation of the lock-free queue from M. Michael and L. Scott described in this paper. An interesting side-note here is that the Java documentation states that it's a wait-free queue, where it's actually lock-free. The Java 8 documentation correctly calls the implementation lock-free.
7. Wait-Free Queues
As we've seen, the above implementation is lock-free, however, not wait-free. The while loops in both the add and get method can potentially loop for a long time (or, though unlikely, forever) if there are many threads accessing our queue.
How can we achieve wait-freedom? The implementation of wait-free algorithms, in general, is quite tricky. We refer the interested reader to this paper, which describes a wait-free queue in detail. In this article, let's look at the basic idea of how we can approach a wait-free implementation of a queue.
A wait-free queue requires that every thread makes guaranteed progress (after a finite number of steps). In other words, the while loops in our add and get methods must succeed after a certain number of steps.
In order to achieve that, we assign a helper thread to every thread. If that helper thread succeeds to add an element to the queue, it will help the other thread to insert its element before inserting another element.
As the helper thread has a helper itself, and, down the whole list of threads, every thread has a helper, we can guarantee that a thread succeeds the insertion latest after every thread has done one insertion. The following figure illustrates the idea:

Of course, things become more complicated when we can add or remove threads dynamically.
8. Conclusion
En este artículo, vimos los fundamentos de las estructuras de datos sin bloqueo. Explicamos los diferentes niveles y operaciones básicas como comparar e intercambiar .
Luego, analizamos una implementación básica de una cola sin bloqueos en Java. Finalmente, describimos la idea de cómo lograr la libertad de espera .
El código fuente completo de todos los ejemplos de este artículo está disponible en GitHub.