Search code examples
javaconcurrencyproducer-consumer

For producer-consumer pattern which implementation is better : ArrayBlockingQueue or Arraylists with Exchangers


Usecase :

its a producer consumer pattern where order (FIFO) is to be maintained. As of now there is single producer and a single consumer to process data in sequential manner to maintain order, but in future ( due to removal of some business constraint ) this requirement of maintaining order will no longer be there. At that time, we will be able create multiple producers and consumer working on same queue.

I can see two solutions :

I can implement data pipes between producer and consumer using a) ArrayBlockingQueue b) Can use Exchangers and use two ArrayListsas underlying data structure

Question :

what are the relative Pros and Cons of these two implementation with respect to concurrancy ?

My thought :

I think Exchangers would be better in terms of concurrency as threads are reading and writing on different ArrayLists but the down side is that producers may have to wait till arraylist of consumer is full and can be exchanged.

thanks in advance for sharing your view.


Solution

  • By no means, ArrayBlockingQueue is better. When using an Exchanger, one of communicating threads would always be blocked, with an ArrayBlockingQueue, blocking occur only producer's and consumer's speeds are unbalanced.

    Using ArrayLists makes sense to reduce contention, and can be used together with ArrayBlockingQueue too.

    UPDATE

    Exchanger.exchange() Waits for another thread to arrive at this exchange point ... and then transfers the given object to it, receiving its object in return.

    That is, the first thread that arrives at the synchronization point always waits. When ArrayBlockingQueue is used, and traffics from producers and to consumers are balanced, no one thread waits.