This:
private final Object lock = new Object();
public void doSomething() {
synchronized (lock) {
// do something
}
}
vs. this:
public void doSomething() {
synchronized (this) {
// do something
}
}
vs. this:
public synchronized void doSomething() {
// do something
}
Here is a great tutorial that explains the different ways of synchronization.
After reading it for me it seems that it's only a matter of taste which one you apply in your code, as all of these have the same consequence, that is: only one thread at a time can do something
. Can you confirm this?
I've read many threads here on SO about synchronization in Java, most of them however are not discussing it in general but specific aspects of it for given snippets of code.
What I'd like to begin with is only to make sure that all three are essentially the same, that I'm not mistaken about the basics, and then I can go on and learn more about the subtle differences in terms of performance and so on...