concurrency vs. synchronization
which way to go? synchronized? ConcurrentHashMap?
After getting up this morning I thought it would be good to contribute something back to my favorite ORM tool: iBATIS. I picked up IBATIS-508 and tried to create a unit test before applying the patch. Unfortunately I was not able to create one so I wanted to do at least some manual testing in order to find out in which way to fix the issue most efficiently. So I created a test case that compares different options for synchronizing access to a resource (namely a map) used by multiple threads at the same time.
The original issue was that the implementation of com.ibatis.common.beans.ClassInfo could cause performance problems under heavy load because of double synchronization. The implementation as of iBATIS 2.3.4 looks like this:
Obviously this is kind of redundant. I was not sure if I should apply the attached patch or just remove the synchronized clause. Therefore I created the test case that can be seen below. The results were:
No synchronization was fastest, with ConcurrentHashMap being also quite fast and the implementation as of 2.3.4 beeing the slowest. Therefore I decided to go for the patch originally attached to the issue. Please see bellow for the complete implementation of the test case. What are the results on your machine? Mine was a Dual Core T7500@2,2 GHZ with 3 GB Ram, Windows XP and Java 1.6.0_13
Please note that ConcurrentHashMap, unlike HashMap, does not allow null values for keys or values. This is not a problem in this use case, I just wanted to warn you.