Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NIO Pipe vs BlockingQueue

Tags:

java

nio

I just discovered that just has an NIO facility, Java NIO Pipe that's designed for passing data between threads. Is there any advantage of using this mechanism over the more conventional message passing over a queue, such as an ArrayBlockingQueue?

like image 525
Maxaon3000 Avatar asked Sep 26 '11 16:09

Maxaon3000


People also ask

Why LinkedBlockingQueue is used in Java?

The LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded. The capacity can be given as a parameter to the constructor of LinkedBlockingQueue.

What is BlockingQueue and where we can use it?

BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

What is blocking and non-blocking queue in Java?

Blocking vs Non-Blocking QueueThe producers will wait for available capacity before adding elements, while consumers will wait until the queue is empty. In those cases, the non-blocking queue will either throw an exception or return a special value, like null or false.


2 Answers

Usually the simplest way to pass data for another thread to process is to use an ExecutorService. This wraps up both a queue and a thread pool (can have one thread)

You can use a Pipe when you have a library which supports NIO channels. It is also useful if you want to pass ByteBuffers of data between threads.

Otherwise its usually simple/faster to use a ArrayBlockingQueue.

If you want a faster way to exchange data between threads I suggest you look at the Exchanger however it is not as general purpose as an ArrayBlockingQueue.

The Exchanger and GC-less Java

like image 124
Peter Lawrey Avatar answered Sep 26 '22 02:09

Peter Lawrey


I believe a NIO Pipe was designed so that you can send data to a channel inside the selector loop in a thread safe way, in other words, any thread can write to the pipe and the data will be handled in the other extreme of the pipe, inside the selector loop. When you write to a pipe you make the channel in the other side readable.

like image 38
chrisapotek Avatar answered Sep 24 '22 02:09

chrisapotek