Let's say I have two critical resources: foo and bar. I protect them with ReentrantReadWriteLock s
ReentrantReadWriteLock foo = new RRWL() ... ReentrantReadWriteLock bar = new RRWL() ...
Most operations use only the foo OR panel, but some of them use both. Now that you are using one lock, you cannot just do this:
void foo() { foo.writeLock().lock(); privateWorkOnFoo(); foo.writeLock().unlock(); }
If an exception is thrown, your foo will be permanently blocked. Instead, you wrap it, for example
void foo() { try { foo.writeLock().lock(); privateWorkOnFoo(); } finally { foo.writeLock().unlock(); } }
But what if I need to work on both? Is it possible to place them in one block?
Option 1
try { foo.writeLock().lock(); bar.writeLock().lock(); magic(); } finally { bar.writeLock().unlock(); foo.writeLock().unlock(); }
Or you want each lock to block its block:
Option 2
try { foo.writeLock().lock(); try { bar.writeLock().lock(); magic(); } finally { bar.writeLock().unlock(); } } finally { foo.writeLock().unlock(); }
I could not be the first person who would have difficulty exploring this before ... I know that option 2 is βbulletproofβ, but it is also much more service. Is option 1 allowed?
source share