...
Code Block | ||
---|---|---|
| ||
final class Flag { private boolean flag = true; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock(); public synchronized void toggle() { writeLock.lock(); try { flag ^= true; // Same as flag = !flag; } finally { writeLock.unlock(); } } public boolean getFlag() { readLock.lock(); try { return flag; } finally { readLock.unlock(); } } } |
Read-write locks allow a shared state to be accessed by multiple readers or a single writer but never both. " Wiki Markup
Wiki Markup In practice, read-write locks can improve performance for frequently accessed read-mostly data structures on multiprocessor systems; under other conditions they perform slightly worse than exclusive locks due to their greater complexity
...
\[[Goetz 06|AA. Java References#Goetz 06]\].
Profiling the application can determine the suitability of read-write locks.
Compliant Solution (AtomicBoolean
)
...