I read this section and this blog article about trying with resource locks as a question popped up in my head. But actually, I would rather try with a lock, I mean without creating an instance. It will free us from detailed
lock.lock(); try { //Do some synchronized actions throwing Exception } finally { //unlock even if Exception is thrown lock.unlock(); }
More likely it will look:
? implements Unlockable lock ; ... try(lock)
Thus, it will not be TWR, but just some kind of cleanup.
Do you have any technical reasons to suggest describing why this would not be a reasonable idea?
EDIT: to clarify the difference between what I suggest and the simple synchronized(lock){} block, check this snippet:
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Test { public static void main(String[] args) { ReentrantLock locker =new ReentrantLock(); Condition condition = locker.newCondition(); Thread t1 = new Thread("Thread1") { @Override public void run(){ synchronized(locker){ try { condition.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Thread1 finished"); } } } ; Thread t2 = new Thread("Thread2") { @Override public void run(){ synchronized(locker){ Thread.yield(); condition.signal(); System.out.println("blabla2"); } } } ; t1.start(); t2.start(); } }
Execution will result in an IllegalMonitorStateException , so the lock () and unlock () methods are implicitly called in the synchronized block.
source share