reentrantreadwritelock java

Solutions on MaxInterview for reentrantreadwritelock java by the best coders in the world

showing results for - "reentrantreadwritelock java"
Febian
04 May 2020
1 class CachedData {
2   Object data;
3   volatile boolean cacheValid;
4   final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
5
6   void processCachedData() {
7     rwl.readLock().lock();
8     if (!cacheValid) {
9        // Must release read lock before acquiring write lock
10        rwl.readLock().unlock();
11        rwl.writeLock().lock();
12        try {
13          // Recheck state because another thread might have
14          // acquired write lock and changed state before we did.
15          if (!cacheValid) {
16            data = ...
17            cacheValid = true;
18          }
19          // Downgrade by acquiring read lock before releasing write lock
20          rwl.readLock().lock();
21        } finally {
22          rwl.writeLock().unlock(); // Unlock write, still hold read
23        }
24     }
25
26     try {
27       use(data);
28     } finally {
29       rwl.readLock().unlock();
30     }
31   }
32 }