0

Does exchanger.exchange() cause thread to move to blocking state. In java docs, it is mentioned that the first thread that reaches the exchanger will be 'waiting' for the second one.

4 Answers 4

3

Exchanger does not block a thread, it causes the first thread reaching the exchanger to wait.

0
2

To be clear, there are six thread states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.

In your scenario, the first thread will go from RUNNABLE to WAITING, and stay in WAITING until the second thread arrives.

The BLOCKED state is used when a thread is blocked while waiting to acquire a mutex. In this particular case, the first thread is the one that acquires the mutex first, and therefore it won't go into BLOCKED state at that point. However, it is possible that the second thread will momentarily go into BLOCKED state when it arrives, or that the first thread will momentarily go into BLOCKED state after receiving the notify.

1

The first thread calling exchange changes it's state to WAITING

A simple code snippet to see what happens:

public class ExchangerTest {

    public static void main(String[] args) throws InterruptedException {
        final Exchanger<Long> ex = new Exchanger<Long>();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread 1");
                try {
                    ex.exchange(10L);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        t1.start();
        Thread.sleep(500); //give t1 time to start
        System.out.println(t1.getState());
    }
}
0

Your answer is in the Javadoc you mentioned yourself. Apparently, the method will block the first thread until the second thread calls the method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.