Before we get into the differences, let's first try and understand what is this
keyword in JAVA. An instance of a class can refer to itself using this
. One can use this
keyword to access class members as well (only non-static ones).
Now synchronization in JAVA is based on Objects
, where each Object
maintains a monitor which allows only one thread to access synchronized
code block (or synchronized
method). Therefore, it is important that same object is shared across different threads in order for them to synchronize correctly.
First version above ensures correct synchronization when same instance of that class is shared across multiple threads.
The second version is basically creating a new Object
every time someMethod
is called, which means even if the same instance of that class was shared across multiple threads, each of those threads would synchronize on different copy of lock
object, thus effectively leading to no synchronization.
To make things a little more clear, here are some other variants of first version.
public void someMethod() {
// Note that assignment below is redundant and is shown for example purposes.
Object lock = this;
synchronized(lock){
//some code
}
}
public synchronized void someMethod() {
//some code
}
As for which version should one select. This totally depends on what method does.
If all operations performed by method requires synchronization, then I prefer to use synchronized
method (last option). This prevents an extra indentation and is slightly more readable. Otherwise, first variant makes sense where you can perform operations that do not require synchronization outside synchronized
block.