Search code examples
javamultithreadingsynchronize

Exchanger : JVM never stops


public static void main(String[] args) throws Exception {
    final Exchanger<String> exchanger = new Exchanger<String>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + exchanger.exchange("this came from subthread"));
            } catch (InterruptedException ex) {
                System.out.println("interrupted while waiting for message");
            }
        }
    }).start();

    System.out.println(Thread.currentThread().getName() + exchanger.exchange("this came from main thread"));
    String s = exchanger.exchange("this came from main thread");
}

Output

mainthis came from subthread
Thread-0this came from main thread

Why does the JVM never quit here?


Solution

  • You have one exchange point in your thread, but 2 exchange points in your main thread. So the second exchange: String s = exchanger.exchange("this came from main thread"); waits forever and prevents the JVM from exiting. If you add a print statement after that line, you will see it does not get executed.

    If you add a second exchange in your thread, the program will exit:

    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + exchanger.exchange("this came from subthread"));
            exchanger.exchange("allow JVM to exit here");
        } catch (InterruptedException ex) {
            System.out.println("interrupted while waiting for message");
        }
    }