In this Q&A, we'll go over how to send and receive messages synchronously using TransferQueue
TransferQueue is a blocking queue interface where producers can wait for consumers to receive elements. It has blocking and non-blocking methods.
Example below uses LinkedTransferQueue class to synchronously transfer and take elements in different threads. One can also use SynchronousQueue - it behaves the same way as LinkedTransferQueue with capacity zero.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
public class LTQTest {
public static void main(String[] args) {
TransferQueue<Integer> tq = new LinkedTransferQueue<>();
ExecutorService producer = Executors.newSingleThreadExecutor();
ExecutorService consumer = Executors.newSingleThreadExecutor();
producer.submit(() -> {
try {
// transfer an element. blocking call
// waits until consumer thread calls take()
tq.transfer(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
consumer.submit(() -> {
try {
// blocking call. waits until the element is in the queue
System.out.println(tq.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.shutdown();
consumer.shutdown();
}
}
Comments
Post a Comment