java syntax: "synchronized (this)"

user822931 picture user822931 · Nov 7, 2012 · Viewed 30.9k times · Source

can you please explain to me this piece of java code? I cannot understand this syntax.

synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
}

Answer

Abubakkar picture Abubakkar · Nov 7, 2012

It means that this block of code is synchronized meaning no more than one thread will be able to access the code inside that block.

Also this means you can synchronize on the current instance (obtain lock on the current instance).

This is what I found in Kathy Sierra's java certification book.

Because synchronization does hurt concurrency, you don't want to synchronize any more code than is necessary to protect your data. So if the scope of a method is more than needed, you can reduce the scope of the synchronized part to something less than a full method—to just a block.

Look at the following code snippet:

public synchronized void doStuff() {
    System.out.println("synchronized");
}

which can be changed to this:

public void doStuff() {
   //do some stuff for which you do not require synchronization
   synchronized(this) {
     System.out.println("synchronized");
     // perform stuff for which you require synchronization
   }
}

In the second snippet, the synchronization lock is only applied for that block of code instead of the entire method.