Multi-Threading : Acquiring a lock on null reference

The lock is acquired on object (not on reference ) .

We can not acquire the lock on null object or reference pointing to null object.

 

public class LockOnNull {

private static Object lock = null;

public static void main(String ar[]) {
sayHello();
}

private static void sayHello() {
synchronized (lock) {
System.out.println(“Inside the synchronized block”);
}
}
}

Output –  NullPointerException 

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *