Java ReentrantReadWriteLocks - how to safely acquire write lock?

前端 未结 12 1747
小蘑菇
小蘑菇 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:27

    What about this something like this?

    class CachedData
    {
        Object data;
        volatile boolean cacheValid;
    
        private class MyRWLock
        {
            private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
            public synchronized void getReadLock()         { rwl.readLock().lock(); }
            public synchronized void upgradeToWriteLock()  { rwl.readLock().unlock();  rwl.writeLock().lock(); }
            public synchronized void downgradeToReadLock() { rwl.writeLock().unlock(); rwl.readLock().lock();  }
            public synchronized void dropReadLock()        { rwl.readLock().unlock(); }
        }
        private MyRWLock myRWLock = new MyRWLock();
    
        void processCachedData()
        {
            myRWLock.getReadLock();
            try
            {
                if (!cacheValid)
                {
                    myRWLock.upgradeToWriteLock();
                    try
                    {
                        // Recheck state because another thread might have acquired write lock and changed state before we did.
                        if (!cacheValid)
                        {
                            data = ...
                            cacheValid = true;
                        }
                    }
                    finally
                    {
                        myRWLock.downgradeToReadLock();
                    }
                }
                use(data);
            }
            finally
            {
                myRWLock.dropReadLock();
            }
        }
    }
    

提交回复
热议问题