0

How does ReentrantReadWriteLock work? Is it a spin-lock?

The question comes from Elasticsearch, when it shows

   java.lang.ThreadLocal$ThreadLocalMap.expungeStaleEntry(Unknown Source)
   java.lang.ThreadLocal$ThreadLocalMap.remove(Unknown Source)
   java.lang.ThreadLocal$ThreadLocalMap.access$200(Unknown Source)
   java.lang.ThreadLocal.remove(Unknown Source)
   java.util.concurrent.locks.ReentrantReadWriteLock$Sync.tryReleaseShared(Unknown Source)
   java.util.concurrent.locks.AbstractQueuedSynchronizer.releaseShared(Unknown Source)
   java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock.unlock(Unknown Source)

in hot threads in all snapshots and cpu usage is high at the same time. It looks like spin-lock.

Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
cybersoft
  • 1,453
  • 13
  • 31

1 Answers1

0

There is a cost associated to thread local data. What you are seeing here is exactly this. You can even see a comment in ReentrantReadWriteLock mentionning this and optimizing it by caching the data of the thread local data:

Comment:

    /**
     * The hold count of the last thread to successfully acquire
     * readLock. This saves ThreadLocal lookup in the common case
     * where the next thread to release is the last one to
     * acquire.
     * [...]
     */
    private transient HoldCounter cachedHoldCounter;

ReentrantReadWriteLock does not use a spin-lock. It uses the Sync object which uses wait/notify (implemented by LockSupport.park(this)) from the AbstractQueueSynchronizer.

  • 1
    Thank you for the answer! Yes, I saw all it... But some people brazenly claimed that the problem is in spin-lock when they see such stacktrace in my question. I made copy of `ReentrantReadWriteLock` without this hold counters in `ThreadLocal`, but I have not had time to test because changing GC have solved our problem, as strange as it may sound... – cybersoft Mar 24 '16 at 05:04
  • Do you mind sharing your implementation without the hold counters in ThreadLocal? I might use it for another problem we are trying to solve. – Pierre-Luc Bertrand Mar 24 '16 at 20:12
  • There is no difficulty in it: http://pastebin.com/jXVyk1Db but it may not work, because there is some logic on these hold counters. Code with this is just commented out, you can look – cybersoft Mar 25 '16 at 15:55