Java Synchronization Interview Questions

Interview Questions on Synchronization are usually very tough to answer. It is very important to understand synchronisation and all the methods and keywords which are related to it.

  1. What is synchronization of threads?
  2. Can you give an example of a synchronized block?
  3. Can a static method be synchronized?
  4. What is the use of join method in threads?
  5. Describe a few other important methods in Threads?
  6. What is a deadlock?
  7. What are the important methods in java for inter-thread communication?
  8. What is the use of wait method?
  9. What is the use of notify method?
  10. What is the use of notifyAll method?
  11. Can you write a synchronized program with wait and notify methods?
  12. What are alternatives to synchronization in java?

What is synchronization of threads?

Since Threads run in parallel, a new problem arises. What if thread1 modifies data which is being accessed by thread2? How do we ensure that different threads don’t leave the system in an inconsistent state? This problem is usually called synchronization problem.

Let’s first look at an example where this problem can occur. Consider the code in the setAndGetSum method.

int setandGetSum(int a1, int a2, int a3) {
    cell1 = a1;
    sleepForSomeTime();
    cell2 = a2;
    sleepForSomeTime();
    cell3 = a3;
    sleepForSomeTime();
    return cell1 + cell2 + cell3;
}

If following method is running in two different threads, funny things can happen. After setting the value to each cell, there is a call for the Thread to sleep for some time. After Thread 1 sets the value of cell1, it goes to Sleep. So, Thread2 starts executing. If Thread 2 is executing “return cell1 + cell2 + cell3;”, it uses cell1 value set by Thread 1 and cell2 and cell3 values set by Thread 2. This results in the unexpected results that we see when the method is run in parallel. What is explained is one possible scenario. There are several such scenarios possible.

The way you can prevent multiple threads from executing the same method is by using the synchronized keyword on the method. If a method is marked synchronized, a different thread gets access to the method only when there is no other thread currently executing the method.

Let’s mark the method as synchronized:

synchronized int setandGetSum(int a1, int a2, int a3) {
    cell1 = a1;
    sleepForSomeTime();
    cell2 = a2;
    sleepForSomeTime();
    cell3 = a3;
    sleepForSomeTime();
    return cell1 + cell2 + cell3;
}

Can you give an example of a synchronized block?

All code which goes into the block is synchronized on the current object.

    void synchronizedExample2() {
        synchronized (this){
        //All code goes here..
        }
    }

Can a static method be synchronized?

Yes. Static methods and block are synchronized on the class. Instance methods and blocks are synchronized on the instance of the class i.e. an object of the class. Static synchronized methods and instance synchronized methods don’t affect each other. This is because they are synchronized on two different things. Consider the example below.

    synchronized static int getCount(){
        return count;
    }

    static int getCount2(){
        synchronized (SynchronizedSyntaxExample.class) {
            return count;
        }
    }

What is the use of join method in threads?

Join method is an instance method on the Thread class. Let's see a small example to understand what join method does. Let’s consider the thread's declared below: thread2, thread3, thread4

ThreadExample thread2 = new ThreadExample();
ThreadExample thread3 = new ThreadExample();
ThreadExample thread4 = new ThreadExample();

Let’s say we would want to run thread2 and thread3 in parallel but thread4 can only run when thread3 is finished. This can be achieved using join method.Look at the example code below: thread3.join() method call forces the execution of main method to stop until thread3 completes execution. After that, thread4.start() method is invoked, putting thread4 into a Runnable State.

thread3.start();
thread2.start();
thread3.join();//wait for thread 3 to complete
System.out.println("Thread3 is completed.");
thread4.start();
Overloaded Join method

Join method also has an overloaded method accepting time in milliseconds as a parameter. In below example, main method thread would wait for 2000 ms or the end of execution of thread4, whichever is minimum.

thread4.join(2000);

Describe a few other important methods in Threads?

Thread yield method

Yield is a static method in the Thread class. It is like a thread saying " I have enough time in the limelight. Can some other thread run next?".

A call to yield method changes the state of thread from RUNNING to RUNNABLE. However, the scheduler might pick up the same thread to run again, especially if it is the thread with highest priority.

Summary is yield method is a request from a thread to go to Runnable state. However, the scheduler can immediately put the thread back to RUNNING state.

Thread sleep method

sleep is a static method in Thread class. sleep method can throw a InterruptedException. sleep method causes the thread in execution to go to sleep for specified number of milliseconds.

What is a deadlock?

Let’s consider a situation where thread1 is waiting for thread2 ( thread1 needs an object whose synchronized code is being executed by thread1) and thread2 is waiting for thread1. This situation is called a Deadlock. In a Deadlock situation, both these threads would wait for one another for ever.

What are the important methods in java for inter-thread communication?

Important methods are wait, notify and notifyAll.

What is the use of wait method?

Below snippet shows how wait is used. wait method is defined in the Object class. This causes the thread to wait until it is notified.

synchronized(thread){
    thread.start();
    thread.wait();
}

What is the use of notify method?

Below snippet shows how notify is used. notify method is defined in the Object class. This causes the object to notify other waiting threads.

synchronized (this) {
        calculateSumUptoMillion();
        notify();
    }

What is the use of notifyAll method?

If more than one thread is waiting for an object, we can notify all the threads by using notifyAll method.

thread.notifyAll();

Can you write a synchronized program with wait and notify methods?

package com.rithus.threads;

class Calculator extends Thread {
    long sumUptoMillion;
    long sumUptoTenMillion;

    public void run() {
        synchronized (this) {
            calculateSumUptoMillion();
            notify();
        }
        calculateSumUptoTenMillion();
    }

    private void calculateSumUptoMillion() {
        for (int i = 0; i < 1000000; i++) {
            sumUptoMillion += i;
        }
        System.out.println("Million done");
    }

    private void calculateSumUptoTenMillion() {
        for (int i = 0; i < 10000000; i++) {
            sumUptoTenMillion += i;
        }
        System.out.println("Ten Million done");
    }
}

public class ThreadWaitAndNotify {
    public static void main(String[] args) throws InterruptedException {
        Calculator thread = new Calculator();
        synchronized(thread){
            thread.start();
            thread.wait();
        }
        System.out.println(thread.sumUptoMillion);
    }
}
Output
Million done
499999500000
Ten Million done

What are alternatives to synchronization in java?

Java introduced a number of new collections using new approaches to concurrency in threads. Refer Java Concurrent Collections for details

If you loved these Questions, you will love our PDF Interview Guide with 400+ Questions.
Download it now!.

400+ Interview Questions in 4 Categories:
  1. Java : Core Java, Advanced Java, Generics, Exception Handling, Serialization, Threads, Synchronization, Java New Features
  2. Frameworks : Spring, Spring MVC, Struts, Hibernate
  3. Design : Design, Design Patterns, Code Review
  4. Architecture : Architecture, Performance & Load Testing, Web Services, REST Web Services,Security, Continuous Integration