Object Level Locking and Class Level Locking in Java

Category: Java   Tags: Java, Java Thread, Java MultiThread, Thread Synchronization, Java Thread Locks

Object Level Locking

Object level locking is about synchronizing a non-static method or non-static code block such that only one thread will execute the code block on given instance of the class. Object level locking make instance level data thread safe.

Object level locking can be implemented as below:

                                public class MyClass {
                                    public synchronized void test() {}
                                }
                            
                                public class MyClass {
                                    private final Object lock = new Object();
                                    public void test() {
                                        synchronized (lock) {

                                        }
                                    }
                                }
                            
                                public class MyClass {
                                    public void test() {
                                        synchronized (this) {

                                        }
                                    }
                                }
                            

Class Level Locking

Class level locking synchronize static method or block so that it can be accessed by only one thread for whole class. For example if you have 100 instance of a class, then only one thread can execute one method or block of any one instance at a time.

Class level locking can be implemented as below:

                                public class MyClass {
                                    public synchronized static void test() {}
                                }
                            
                                public class MyClass {
                                    private final static Object lock = new Object();
                                    public void test() {
                                        synchronized (lock) {

                                        }
                                    }
                                }
                            
                                public class MyClass {
                                    public void test() {
                                        synchronized (MyClass.class) {

                                        }
                                    }
                                }
                            

Class level locking is used to safe static data.