TransferQueue Vs SynchronousQueue

TransferQueue is pretty much the same as SynchronousQueue however allowing the functionality of the SynchronousQueue to be inside the transfer() method

For example the following code will hang:

public class Application {
  public static void main(String[] args) throws InterruptedException {
    TransferQueue<Integer> map = new LinkedTransferQueue<>();

    map.transfer(12);
    map.put(13);
    map.put(14);

    System.out.println(map.take());
    System.out.println(map.take());
    System.out.println(map.take());
  }
}

However the following code will success:

public class Application {
  public static void main(String[] args) throws InterruptedException {
    TransferQueue<Integer> map = new LinkedTransferQueue<>();

    map.put(12);
    map.put(13);
    map.put(14);

    System.out.println(map.take());
    System.out.println(map.take());
    System.out.println(map.take());
  }
}

For the transfer() above, we need another thread to take it for example

package misc;

import java.util.concurrent.*;

public class Application {
  public static void main(String[] args) throws InterruptedException {
    TransferQueue<Integer> map = new LinkedTransferQueue<>();

    ExecutorService executorService = Executors.newCachedThreadPool();

    executorService.submit(() -> {
      try {
        map.transfer(12);
        map.put(13);
        map.put(14);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    });

    System.out.println(map.take());
    System.out.println(map.take());
    System.out.println(map.take());

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.DAYS);
  }
}