Java ReentrantReadWriteLocks - how to safely acquire write lock?

前端 未结 12 1748
小蘑菇
小蘑菇 2020-11-28 19:00

I am using in my code at the moment a ReentrantReadWriteLock to synchronize access over a tree-like structure. This structure is large, and read by many threads at once wit

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 19:37

    So, Are we expecting java to increment read semaphore count only if this thread has not yet contributed to the readHoldCount? Which means unlike just maintaining a ThreadLocal readholdCount of type int, It should maintain ThreadLocal Set of type Integer (maintaining the hasCode of current thread). If this is fine, I would suggest (at-least for now) not to call multiple read calls within the same class, but instead use a flag to check, whether read lock is already obtained by current object or not.

    private volatile boolean alreadyLockedForReading = false;
    
    public void lockForReading(Lock readLock){
       if(!alreadyLockedForReading){
          lock.getReadLock().lock();
       }
    }
    

提交回复
热议问题