SynchronousQueue
SynchronousQueue (Java Platform SE 8 ) (oracle.com)
java.util.concurrent.SynchronousQueue<E>
Has no capacity, each put
needs to wait for a corresponding take
operation
Example
For exmample, something like this would hang
package misc;
import java.util.concurrent.*;
public class Application {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> map = new SynchronousQueue<>();
map.put(12);
map.put(13);
map.put(14);
System.out.println(map.take());
System.out.println(map.take());
System.out.println(map.take());
}
}
The reason is there is no other thread that's trying to take the 12
.
To fix it, we need to call put
in a separate thread
package misc;
import java.util.concurrent.*;
public class Application {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> map = new SynchronousQueue<>();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(() -> {
try {
map.put(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);
}
}