Hi all whenever I use the synchronized statement, I often use this pattern:
private static Object lock = new Object();
public void F(){
//..
synchronized (lock){
//..
}
//..
}
However, in the source of java.lang.Reference, I see that they employ this pattern instead:
static private class Lock { };
private static Lock lock = new Lock();
public void run() {
//..
synchronized(lock){
//..
}
//..
}
I was wondering what’s the benefit of declaring a new class Lock (which basically extends Object and do nothing else) ?
Or rather, why didn’t they simply use private static Lock lock = new Object(); ?
The following code:
doesn’t actually use the
Lockmechanics, you’re just using the built-in synchronisation features on anObject. In this case, you might as well use a plain oldObject. A benefit of a lock object that extendsObjectis so that it shows up in debugging tools with the class name rather than just a plainObject, which is more helpful when hunting down deadlocks.See here for the
LockAPI.The benefit of
Lockis that you get more features, such as being able to ‘try’ locking, then continuing to execute code if that fails. Also, it has different properties than a synchronized block, because it’s not reentrant (a thread can’t hold multiple locks on the same lock, then release them). If you wanted something that was like that, you’d useReentrantLock.You also have cooler locks such as
ReentrantReadWriteLock, which support multiple readers, but as soon as a writer locks it, no readers are permitted. There’s a big lock ecosystem in there for different types of application.