Wednesday, September 25, 2013

Java: SynchronousQueue vs LinkedBlockingQueue/ArrayBlockingQueue

I recently came across some legacy code which used SynchronousQueue to transfer data between threads. Since I have almost always used ArrayBlockingQueue ( bounded size) or LinkedBlockingQueue ( for unbounded sizes ) I could not understand the rationale for using the SynchronousQueue. I did look at the source code for SynchronousQueue and it looks like there is no real underlying queue at all. Instead there seems to be a handoff semantic with an implicit queue size of just 1. After one put() on the queue, the queue.put() blocks until a consumer is available to remove from the queue.

I ran a simple experiment to see how throughput could vary across these 3 queues. For this test objects put into the queue were Integers, Xms=512m and Xmx=1024m. I used Java 1.7.0_17.

Hardware used: Windows 7-64-bit,8 gb ram, Core i5 CPU, 2.53 Ghz
The LinkedBlockingQueue and ArrayBlockingQueue were set to a capacity of 1 to have a apples-to-apples comparison. I ran multiple tests varying the number of puts in the queue.

Results:
As you can see from the table below, for a capacity of 1, the Synchronousqueue seemed to provide extremely good throughput when compared to a unit sized blocking or linked queue. The SynchronousQueue, under this condition, is about 7x-10x faster than the other 2 blocking queue implementations.


No comments:

Post a Comment