The following code:
synchronized(lock){ }
doesn't actually use Lock
mechanics, you just use the built-in synchronization functions on Object
. In this case, you can use a plain old Object
. The advantage of a lock object extending Object
is that it appears in the debugging tools with the class name, and not just with the regular Object
, which is more useful when looking for deadlocks.
See here for API Lock
.
The advantage of Lock
is that you get more options, for example, the ability to "try" to lock, and then continue to execute code if it fails. In addition, it has different properties than a synchronized block, because it is not reentrant (a thread cannot hold several locks in one lock, and then release them). If you want something like this, use ReentrantLock
.
You also have cooler locks, such as ReentrantReadWriteLock
, that support multiple readers, but as soon as the writer locks it, no readers are allowed. There is a large blocking ecosystem for various types of applications.
Chris dennett
source share