Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SynchronousQueue Vs Exchanger

Whats the difference between Exchanger and SynchronousQueue? And the scenarios in which each of them can be used? Which one is better performance wise? (Lock wise?)

like image 275
Hemanshu Avatar asked Mar 16 '12 10:03

Hemanshu


1 Answers

An Exchanger is more of a pure synchronization mechanism while a SynchronousQueue additionally offers all operations of a standard queue data structure. This means that you can for example check what objects are in queue, cancel scheduled but not yet executed actions by removing items from the queue asynchronously etc. - operations an Exchanger doesn't offer. Since many implementations allow setting a limit on queue size, you get additional control over your resource usage and can drop requests if the queue grows above a certain threshold. On the other hand, the Exchanger offers two-way communication out of the box while a single queue is just one way (though one can implement communication in the other direction manually). Since many practical situation require just a producers-consumers relationship, a queue is often better because of an easier to understand API and additional operations listed above.

This article describes a practical use case for Exchanger. They concentrate on being able to avoid creating and garbage collecting new objects when communicating between threads (depending on implementation, queues may allocate entries when you append something to them). Performance will probably depend on your particular use case. In the example they use Exchanger for efficiency (avoiding garbage collection), but in most cases (if you don't have to provide sub-millisecond latencies) allocating an object or two isn't such a big issue and I'd prefer using a queue for the extra control it allows.

EDIT: I checked the source for Exchanger.java in Oracle JDK and it does create temporary objects of class Exchanger.Node in Exchanger.doExchange(). So it seems that contrary to what authors of the linked article state, Exchanger isn't allocation-free. Neither is (rather obviously) LinkedBlockingQueue. The ArrayBlockingQueue, in contrast, doesn't allocate any temporary objects when an item is appended to it. It only allocates an array to hold the maximum allowed number of elements when it is created, but that's just a one-time operation. During use, it doesn't create new objects, so from the pure GC point of view it should be better than Exchanger.

like image 119
Michał Kosmulski Avatar answered Oct 19 '22 14:10

Michał Kosmulski