Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
How to use the synchronized keyword?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: How to use the synchronized keyword?

How to use the synchronized keyword?

There are two syntactic forms based on the synchronized keyword, methods and blocks. A synchronized method acquires a lock before it executes. For example, the following synchronized method

class MyClass {
   public synchronized void function() {
          ....
   }
}

is equivalent to the following synchronized block

class MyClass {
   public void function() {
        synchronized(this) {
          ....
        }
   }
}

Few notes about synchronized keyword:

  • The constructors and initializers cannot be synchronized and a compiler error will occur if you put synchronized front of a constructor. But constructors and initializers of a class can contain synchronized blocks. For example,
    class MyClass {
       static int x = 0;
       static int y = 0;
       
       {
            synchronized(MyClass.class) {
              x++;
            }
       }
    
       public MyClass() {
            synchronized(MyClass.class) {
              y++;
            }
       }
    }
    
  • The synchronized keyword is not part of the method signature. Therefore, it is not automatically inherited when subclasses override superclass methods. The synchronized methods can be overrided to be non-synchronous. The synchronized instance methods in subclasses use the same locks as their superclasses.
  • The interface's methods cannot be declared synchronized.
  • The synchronization of an Inner Class is independent on it's outer class. That means locks on inner/outer objects are independent. Getting a lock on outer object doesn??t mean getting the lock on an inner object as well, that lock should be obtained separately
  • A non-static inner class method can lock it's containing class by using a synchronized block. The inner class can reference the outer class with OuterClass.this:
        synchronized(OuterClass.this) {
            ....
        }
    

Reference

Concurrent Programming in Java : Design principles and patterns by Doug Lea

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help