Given that there's only one lock for each instance of a class, then why doesn't Java just allow us to do this:
void method() {
synchronized {
// do something
}
// do other things
}
instead of this:
void method() {
synchronized (lock) {
// do something
}
// do other things
}
What's the purpose of specifying a lock? Does it make a difference if I choose one object as a lock over the other? Or could I just choose any random object?
EDIT:
It turned out that my comprehension of synchronized methods is wrong at the fundamental level.
I thought different synchronized methods or blocks are entirely independent of each other regardless of locks. Rather, all synchronized methods or blocks with the same lock can be accessed only by one thread, even if such synchronized methods/blocks are from different classes (the documentation should have emphasized this more: ALL synced methods/blocks, regardless of location, all that matters is the lock).
Although an intrinsic lock is provided with each instance, that's not necessarily the "obvious" lock to use.
You're perhaps right that they could have provided
synchronized { ... }
as a shorthand forsynchronized (this) { ... }
. I don't know why they didn't, but I never missed it. But concurrent programming is tricky, so making the lock object an explicit required parameter may make things clearer to readers, which is a good thing, as @ajb pointed out in a comment. In any case, I don't think syntax is your main question, so let's move on.Uhm, the lock is perhaps the single most important thing in the synchronization mechanism. The key point in synchronization is that only one thread can hold the same lock. Two threads holding different locks are not synchronized. So knowing what is the lock guarding the synchronization is crucial.
I hope the previous section makes it clear that yes, you have to choose the object carefully. It has to be an object visible by all threads involved, it has to be not null, and it has to be something that won't get reassigned during the period of synchronization.
Certainly not. See the previous section.
To understand concurrency in Java, I recommend the book Java Concurrency in Practice by one of the authors of the API, or Oracle's tutorials on the subject.