In Java, do ReentrantLock.lock()
and ReetrantLock.unlock()
use the same locking mechanism as synchronized()
?
My guess is \"No,\" b
No, Thread 2 can lock()
even when Thread 1 is synchronized
on the same lock
. This is what the documentation has to say:
Note that Lock instances are just normal objects and can themselves be used as the target in a synchronized statement. Acquiring the monitor lock of a Lock instance has no specified relationship with invoking any of the lock() methods of that instance. It is recommended that to avoid confusion you never use Lock instances in this way, except within their own implementation.
Why did you make the balance static in Account class? Remove static and it should work.
Also, have a question about your thread usage. In your TestMain you create new threads and assign runnables like WithdrawRequests & DepositRequests. But again you create new threads inside the constructors of those runnables. This will cause the run method to be executed twice!
The two mechanisms are different. Implementation/performance wise:
Under some circumstances, the explicit locks can perform better. If you look at this comparison of locking mechanisms I performed under Java 5, you'll see that in that particular test (multiple threads accessing an array), explicit lock classes configured in "unfair" mode (the yellow and cyan triangles) allow more throughput than plain synchronized (the purple arrows).
(I should also say that the performance of synchronized has been improved in more recent versions of Hotspot; there may not be much in it on the latest versions or indeed under other circumstances-- this is obviously one test in one environment.)
Functionality-wise: