Wednesday, 3 July 2013

Threading, Synchronization

Q1. Explain transient modifier.
Ans. When an instance variable is declared as transient, then its value need not persist when an object is stored. For example: file handle, a database connection, a system thread etc.
class T {
     transient int a; // will not persist
     int b; // will persist}


Such objects are only meaningful locally. So they should be marked as transient in a serializable class.

Q2. Can a method be static and synchronized?
Ans. A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.Class instance associated with the object. It is similar to saying:
               synchronized(XYZ.class) { ....}

Q3. How to make thread safe singleton.
Ans.
1. Synchronize the getInstance() method.

2. Second approach to thread safety declares a constant Singleton attribute on the Singleton class itself:public class Singleton {
      public final static Singleton instance = new Singleton();
      private Singleton() {};

      public static void main( String [] args ) {
            Singleton instance = Singleton.instance;            // ...
      }
}
Variable “instance” will be initialized when the class loads. 

3. Third approach is to use synchronized block
public class ExampleSingleton {
      private static ExampleSingleton instance;

      public static ExampleSingleton getInstance() {

            // non-synchronized to prevent locking in case instance has already been created
            if ( instance == null ) {
                  synchronized( ExampleSingleton.class ) {

                        // Synchronized to prevent pre-emption and checking for is-nullable again
                        // to ensure that object is not created and not in stage of creation)
                        if ( instance == null ) { 
                             instance = new ExampleSingleton();
                        }
                  }//sync ends
            }
            return instance;
      }
}



No comments:

Post a Comment