SCJP(94%)
Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).
A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such specialized semantics then the implementation must document those semantics.
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.
Gabriel Vargas
SCJP, SCJD, now studying for SCWCD and working to be a better person
SCJP(94%)
Compiles but it is a bad programming practice because you use a Lock object as a monitor and javadoc of Lock class prevents it because generates confusion.
Gabriel Vargas
SCJP, SCJD, now studying for SCWCD and working to be a better person
SCJP(94%)
SCJP(94%)
SCJP(94%)
I guess the difference is that
if you use synchronized(this), you lock every thing in this object.
So you can achieve synchronized(this) with synchronized(lock), but it is not true the other way around
Gabriel Vargas
SCJP, SCJD, now studying for SCWCD and working to be a better person
Consider Paul's rocket mass heater. |