Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are class level, object level, explicit and intrinsic locking?

I have been going through Java multi-threading concepts. The more I go through them, the more confused I become.

Right now I am not understanding the differences between class level, object level, explicit and intrinsic locking in Java. Can someone please let me know which is what? Also, if I can get some examples to understand, that will be very helpful for me.

like image 481
The Dark Knight Avatar asked Sep 30 '22 12:09

The Dark Knight


1 Answers

Explicit vs Intrinsic

When you use synchronized on an object or indirectly as part of a method signature you are creating an intrinsic lock. You rely upon the in-built lock associated with all objects and classes.

An explicit lock is provided in Java 5+ in the package java.util.concurrent.locks. The most commonly used class is probably ReentrantLock. These provide alternatives to using the intrinsic locks and offer features that are not possible with intrinsic locks.

Class Level vs Object Level

This distinction applies to intrinsic locks only. If you have a synchronized static method, the intrinsic lock used will be associated with the class object itself. If you synchronize on an object instance (or have a synchronized instance method) it will be an object-level lock.


Further Reading

Brian Goetz's Java Concurrency in Practice is an excellent book for understanding the nightmarishly confusing world of multi-threaded programming in Java.

like image 54
Duncan Jones Avatar answered Oct 03 '22 03:10

Duncan Jones