Deep Dive into Java’s Exchanger: How It Works and When to Use It

This article explains Java's Exchanger class, detailing its synchronization mechanism, internal source‑code structure, practical usage examples, and how it compares with other concurrency utilities such as CyclicBarrier, Semaphore, and SynchronousQueue.

Programmer1970
Programmer1970
Programmer1970
Deep Dive into Java’s Exchanger: How It Works and When to Use It
Java's concurrent programming requires thread data exchange and synchronization; the JUC library provides Exchanger for this purpose.

1. Overview of Exchanger

Exchanger is a synchronization point that allows two threads to exchange data. Each thread calls exchange with an object and waits for the counterpart. When both threads reach the exchange point, the data are swapped safely and execution continues.

2. Working Principle

The mechanism relies on a wait‑notify scheme. The first thread stores its data in a slot and blocks. The second thread, upon calling exchange, retrieves the first thread’s node, swaps the data, and wakes the first thread. Both threads then obtain the other's data.

Note: Exchanger works only between two threads. For more than two participants, other synchronization tools or more complex logic are required.

3. Source Code Analysis

The implementation uses an internal waiting queue (simplified as a single node). The first arriving thread is placed in slot and blocks; the second thread removes the node, performs the exchange, and both continue.

public class Exchanger<V>{
    // simplified waiting node
    private volatile Node<V> slot;
    // ... other fields and methods ...

    public Exchanger(){
        slot = null;
    }

    public V exchange(V x) throws InterruptedException{
        // create a new node with current thread and data
        Node<V> newNode = new Node<V>(Thread.currentThread(), x);
        // spin until exchange succeeds
        for(;;){
            Node<V> oldNode = slot;
            if(oldNode == null){
                if(compareAndSetSlot(null, newNode)){
                    // wait for another thread
                    waitForMatch(newNode);
                    return newNode.item; // exchanged data
                }
            } else if(oldNode.isWaiting()){
                if(compareAndSetSlot(oldNode, null)){
                    newNode.match = oldNode;
                    // wake waiting thread
                    oldNode.thread.interrupt();
                    return oldNode.item; // exchanged data
                }
            } else {
                // slot already matched, spin or wait
            }
        }
    }

    private static final class Node<V>{
        final Thread thread; // thread reference
        V item;               // data to exchange
        Node<V> match;        // partner node

        boolean isWaiting(){
            return match == null;
        }
    }

    private boolean compareAndSetSlot(Node<V> expect, Node<V> update){
        // ... CAS implementation ...
        return true;
    }

    private void waitForMatch(Node<V> newNode) throws InterruptedException{
        // ... wait/notify logic ...
    }
}

The class also uses wait and notify inside the internal node to handle thread blocking and waking. Advanced features such as interrupt response and timed waiting are supported.

4. Application Scenarios

4.1 Use Cases

Exchanger is useful in genetic algorithms for exchanging individuals, in pipeline designs for passing data blocks or tasks, and in games for player item trades. It can also implement alternating execution between two threads or a bidirectional producer‑consumer pattern.

4.2 Example

The following program demonstrates two threads swapping string data:

import java.util.concurrent.Exchanger;

public class ExchangerExample{
    public static void main(String[] args){
        Exchanger<String> exchanger = new Exchanger<>();

        Thread producer = new Thread(() -> {
            try{
                String producedData = "Hello";
                String consumerData = exchanger.exchange(producedData);
                System.out.println("Producer received: " + consumerData);
            }catch(InterruptedException e){
                Thread.currentThread().interrupt();
            }
        }, "Producer");

        Thread consumer = new Thread(() -> {
            try{
                String consumerData = "World";
                String producedData = exchanger.exchange(consumerData);
                System.out.println("Consumer received: " + producedData);
            }catch(InterruptedException e){
                Thread.currentThread().interrupt();
            }
        }, "Consumer");

        producer.start();
        consumer.start();
    }
}

Both threads block on exchange() until the counterpart arrives, then each receives the other's string and prints it. The output is:

Producer received: World
Consumer received: Hello

5. Comparison with Other Synchronization Tools

Compared with CyclicBarrier, Exchanger focuses on data exchange rather than simple barrier synchronization. Compared with Semaphore, it provides direct data swapping instead of resource‑access control. Compared with SynchronousQueue, Exchanger can be seen as a bidirectional simplification of that queue.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencyJUCThread SynchronizationExchangerJava Util Concurrent
Programmer1970
Written by

Programmer1970

Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.