3

I have some storage similar to a map. I have been using synchronized(this) for get and put methods. Since this storage is mostly used for reading, I thought of using ReentrantReadWriteLock for better performance - to lock only on put.

I expected better performance on lookups (since storage content was not changed). However, my JMH test shows the opposite:

.benchmarkClassMap3ClassLookup    thrpt       20    460.152        7.417  ops/ms
.benchmarkClassMapClassLookup     thrpt       20   1196.085       23.635  ops/ms

The first line is for the code using ReentrantReadWriteLock. The second line is for the original code, with synchronized. EDIT: test was running with 2 threads.

Did anyone else benchmarked ReentrantReadWriteLock? Shouldn't be the results different? Or do the positive result only show up in the multi-threaded environment?

Related: this.

Community
  • 1
  • 1
igr
  • 10,199
  • 13
  • 65
  • 111

1 Answers1

4

You will need for sure multiple threads to see a benefit because ReentrantReadWriteLock is more complex than the simple synchronized. In case of synchronized the JVM might optimize and remove the synchronization all together if it sees that there is only one thread. But here is also a quote from ReentrantReadWriteLock javadoc:

ReentrantReadWriteLocks can be used to improve concurrency in some uses of some kinds of Collections. This is typically worthwhile only when the collections are expected to be large, accessed by more reader threads than writer threads, and entail operations with overhead that outweighs synchronization overhead.

If you afford to move to Java 8 you can replace ReentrantReadWriteLock with the new StampedLock that came with this release. See this answer for a short example and benefits.

Community
  • 1
  • 1
dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
  • 1
    Thanx. I made a mistake, my tests were running with 2 active threads. BTW, here is an [interesting article](http://www.javacodegeeks.com/2014/06/java-8-stampedlocks-vs-readwritelocks-and-synchronized.html) – igr Sep 28 '14 at 20:05