what is the class level synchronization.If the class is locked by one thread at same other thread can access the other method of that class

There is a class EmployeeInfo it has a static synchronized method non static synchronized method

public class EmployeeInfo{
    public static synchronized void insert(){
        //Insert code
    }

    public synchronized void update(){
        //update code
    }

    public void delete(){
        //update code
    }
}

There are five threads A, B, C, D, and E. Every thread is running.

A thread comes and accesses the method insert() of class EmployeeInfo.

At the same time:

  • Now B thread come and try to access insert() method again - what will happen?
  • Now C thread come and try to access update() - what will happen?
  • Now D thread come and try to access delete() - what will happen?

Please explain the concept of class level synchronization following the above example.

Jon Skeet
people
quotationmark

There are two separate locks involved here - one for the instance on which you call update, and one for the class itself. So thread B would be blocked until thread A had completed, but the other two threads would execute without blocking. (D isn't synchronizing on anything anyway.)

Your code is broadly equivalent to:

public class EmployeeInfo{
    public static void insert(){
        synchronized (EmployeeInfo.class) {
            // Insert code
        }
    }

    public void update() {
        synchronized (this) {
            // Update code
        }
    }

    public void delete() {
        // Note: no synchronization
        // Delete code
    }
}

people

See more on this question at Stackoverflow