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.
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.
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.
Brian Goetz's Java Concurrency in Practice is an excellent book for understanding the nightmarishly confusing world of multi-threaded programming in Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With