class Exchanger { T ex1 = null; T ex2 = null; public synchronized T exchange(T obj) throws InterruptedException { T res = null; while (ex2 != null) wait(); if (ex1 == null) { ex1 = obj; while (ex2 == null) wait(); res = ex2; ex2 = null; } else { ex2 = obj; res = ex1; ex1 = null; } notifyAll(); return res; } }