Wednesday, March 14, 2012

Explain synchronized keyword in Java?


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++;
            }
       }
    }
  • Although the synchronized keyword can appear in a method header, 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 is part of the implementation but not part of the interface.
  • 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) {
            ....
        }

No comments:

Post a Comment