Java - Threads - Synchronization - Interview Questions and Answers on Lock and Locking

Q1.  Can a lock be acquired on a class ?

Ans. Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

Q2.  What is an object's lock and which object's have locks?

Ans. An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q3.  What is a ConcurrentHashMap ?

Ans. ConcurrentHashMap is a hashMap that allows concurrent modifications from multiple threads as there can be multiple locks on the same hashmap.

Q4.  What is the use of double checked locking in createInstance() of Singleton class?

Double checked locking code:
public static Singleton createInstance() {
     if(singleton == null){
      synchronized(Singleton.class) { 
              if(singleton == null) {
         singleton = new Singleton();
      }
   }
  }
   return singleton;
}

Single checked locking code:
public static Singleton createInstance() {
      synchronized(Singleton.class) { 
              if(singleton == null) {
         singleton = new Singleton();
      }
   }
   return singleton;
}

What advantage does the first code offer compared to the second ?

Ans. In First Case , Lock for the synchronized block will be received only if 
singleton == null whereas in second case every thread will acquire the lock before executing the code.

The problem of synchronization with singleton will only happen when the object has not be instantiated. Once instantiated , the check singleton == null will always generate true and the same object will be returned and hence no problem. First condition will make sure that synchronized access ( acquiring locks ) will only take place if the object has not been created so far.

Q5. Lock is a / an ...

 a.Abstract Class
 b.Concrete Class
 c.Interface
 d.Package

Ans.Interface

Q6. Name few classes that implement Lock interface?

Ans.[ReentrantReadWriteLock.WriteLock,ReentrantLock, ReentrantReadWriteLock.ReadLock]