Java Interview Reference Guide – Synchronization


The synchronized modifier is used to control access to critical code in multi-threaded program. The synchronized keyword is one of the tools that make your code thread safe. The “Synchronized” modifier in Java prevents concurrent access code block or methods by multiple threads. Synchronized force threads to obtain a lock before entering the method and release the lock after completing the method. It ensures that only one thread can execute the method at a time.

If we make method or block as synchronized then it will not allow more than one invocations on synchronized method on the same object. If one method invoke synchronized method other thread block until the first thread complete the method execution.

First method acquires the lock of that object before entering the synchronized method of the same object and releases it to acquire by other threads. Synchronize method use happens-before relationship, which guarantees that changes to the state of object are visible to all threads

When you mark a block of code as synchronized you use an object as a parameter. When an executing thread comes to such a block of code, it has to first wait until there is no other executing thread in a synchronized block on that same object. However a thread could enter the block of synchronized method other object. But non-synchronized method in same object can access without checking lock.

if you synchronize on a static method you will synchronize on the class (object) and not on an instance (object). That means while execution of a static method the whole class is blocked. So other static synchronized methods are also blocked

1) When a thread has entered a synchronized instance method then no other thread can enter any of synchronized instance methods of the same instance

2) When a thread entered a synchronized static method then no other thread can enter any of synchronized static methods of the same class

Note: No link between synchronized static methods and non static methods that means Static synchronize and non-static synchronize method can run concurrently unless your non-static method must explicitly synchronize on the class itself (ie, synchronized (MyClass.class) {…}

Note: Constructor of class cannot be synchronized.

Monitor or Intrinsic Lock

 Intrinsic locks enforce restriction on access to an object’s state and establish happens-before relationships.

Every object has an intrinsic lock and a thread has to acquire the object’s intrinsic lock before accessing them and release it when it’s done. Other thread cannot access the object’s state till thread owns its intrinsic lock. It ensure that state change done by a thread will be visible to other thread which synchronize on the same monitor.

After thread release lock which effect of flushing the cache to main memory so that object’s state change will be visible to other thread and that is called happens-before relationship.

The synchronized and volatile constructs, as well as the Thread.start () and Thread.join() methods, can form happens-before relationships.

The locks acquired by synchronized statements are the same as the locks that are acquired implicitly by synchronized methods. A single thread may acquire a lock more than once.

Acquiring the lock associated with an object doesn’t prevent other threads for accessing fields of the object or invoking un-synchronized methods.

The synchronized statement attempts to seek lock of object and the body of synchronized statements executed once it acquire lock of that object and unlock after completing the synchronized statements.

If the method is member or instance of object then it will lock instance for which it was invoked. If the method is static, it locks the monitor associated with the Class object that represents the class in which the method is defined. Synchronize method control by its property-SYNCHRONIZED flag, which is check by method invocation instructions.

Atomic Variable

If we consider int i++ it contains combination of multiple operation e.g. it reads value from memory, increment and puts write back to the memory. This operation is fine for single thread operation but might give wrong answer in multi-thread environment. It also have race issue means multiple thread can read the value at the same time.

Atomic access ensures that action happens all at once. An atomic action occurs completely or doesn’t occur at all.

There are actions you can specify that are atomic:

  1. Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  2. Reads and writes are atomic for all variables declared volatile (including long and double variables).

The java.util.concurrent.atomic package defines classes that support atomic operations on single variables. All classes have get and set methods that work like reads and writes on volatile variables. That means, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables .

In java 5.0 java.util.concurrent.atomic package define classes that supports atomic operation on single operation. The JVM compiles these classes with the better operations provided by the hardware machine, CAS (Compare and Set).

  • AtomicInteger
  • AtomicLong
  • AtomicBoolean
  • AtomicReference

All classes have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables

Volatile variable

Only variable may be volatile. Such variable might be modified asynchronously so the compiler takes special precaution

The volatile modifier guarantees that any thread that reads a field will see the most recently written value

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable are always visible to other threads. What’s more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

In a multi thread environment object make their own copy of object in threads local cache except volatile variable that means volatile will have only one copy in heap which will updated by thread and immediately reflect to other Thread. There is no flush of local’s thread cache memory after completing the process.

Volatile fixed visibility issue but bring race condition and it will not lock to wait to complete the process for example :

Volatile int i=0

i +=5 invoking by two simultaneously thread give result 5 or 10 but it guarantee to see immediate changes.

Use of volatile: One common example for using volatile is to use a volatile boolean variable as a flag to terminate a thread.


Difference between static and volatile variable

Declaring static variable means there will be only copy associated with class it doesn’t matter how many object get created for that class. The static variable will be accessible even with no Objects created at all. Thread may have locally cached values of it.

This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the threads has in cache an old value. Even if you access a static value through multiple threads, each thread can have its local cached copy!

But a volatile variable will keep only one copy in memory and shared across the threads.

 Difference between Volatile and Synchronize:

So where volatile only synchronizes the value of one variable between thread memories and “main” memory, synchronized synchronizes the value of all variables between thread memory and “main” memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in “main” memory. Effectively, a variable declared volatile must have it’s data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value.

Lock Objects

Lock object behave same as implicit locks, which is used by synchronized code. As with implicit locks, only one thread can own a Lock object at a time. Lock objects also support a wait/notify mechanism, through their associated condition object.

The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock. The tryLock() method backs out if the lock is not available immediately or before a timeout expires (if specified). The lockInterruptibly() method backs out if another threads sends an interrupt before the lock is acquired

 Java garbage collector

Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (i.e. background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you can’t force it.

How to write a Deadloack

In some cases in multi thread environment deadlock situation occured means two or more thread are blocked forever, waiting for each other.
Below sample code is an deadlock scenarios:

public class DeadlockSample {
private final Object obj1 = new Object();
private final Object obj2 = new Object();

public static void main(String[] args) {
DeadlockSample test = new DeadlockSample();

private void testDeadlock() {
Thread t1 = new Thread(new Runnable() {
public void run() {
Thread t2 = new Thread(new Runnable() {
public void run() {

private void calLock12() {
synchronized (obj1) {
synchronized (obj2) {
private void calLock21() {
synchronized (obj2) {
synchronized (obj1) {
private void sleep() {
try {
} catch (InterruptedException e) {

Explain types of references in Java?

java.lang.ref package can be used to declare soft, weak and phantom references

  • Garbage Collector won’t remove a strong reference.
  •  A soft reference will only get removed if memory is low. So it is useful for implementing caches while avoiding memory leaks.
  •  A weak reference will get removed on the next garbage collection cycle.  Can be used for implementing canonical maps. The java.util.WeakHashMap implements a HashMap with keys held by weak references.

A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.

Effective Java™


3 thoughts on “Java Interview Reference Guide – Synchronization

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s