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.
lockgets initialized each time the method is being invoked. Now each thread will create a different object and hence it will not be shared. Now whatever critical statements you have within synchronized block will be guarded by different lock objects. You have multiple threads working on same critical section at same time and synchronization although applied is not effective at all.thisis shared by all the instance methods. It is not something which is local to a method. Hence synchronization works. Multiple threads will access critical section of code guarded by synchronized block onthiswill enter critical section at a time asthisis shared by all the threads entering an instance methodthismeans. But, what we have here is a question about whatsynchronizedmeans.synchronized(obj)does not protectobjfrom access by other threads. The main thing it does is, it stops other threads from entering any block of code that is synchronized on the same object. You can use that feature to protectobjor, you can use it to protect any other variables. But, it's up to you to ensure that the variable (or variables) that you want to protect are only ever accessed from insidesynchronizedblocks that all synchronize on the same object.