People talk about two types of multithreaded locking - an object and a class.
A class is an object. In Java, there is only one type of lock: each object (including each class) has a mutex that can be locked by a synchronized or synchronized block. The object to be locked is implicit in the synchronized method: it is an instance of "this" for the instance method, and a class object for the static method.
One of the most common beginner mistakes is to think that two different threads cannot get into the same synchronized block at the same time. They can, and there are many questions and answers here on StackOverflow that prove this. Another mistake is to think that if one thread is synchronized on an object, then other threads will not be able to modify the object. They can and they do it.
Synchronization prevents the simultaneous synchronization of two or more threads on the same object. Which object is the correct object? All about protecting your data. If the structure you want to protect is a linked list, for example, then a good choice would be for any method that accesses the list for synchronization in the list header. If you want to protect global data (for example, static variables), you want to synchronize the global object (for example, the class object to which the variables belong). The important thing is that if you have read / write data (aka, "mutable data") that is accessed by more than one thread, then every method that accesses the same data must synchronize with the same lock.
In Java, there is another kind of lock, but not in Java; this is in the standard java library. It is accessible through objects that implement the java.util.concurrent.locks.Lock interface. Of course, the Lock object (like any object) also implements the first type of lock, but you should never synchronize on the Lock object unless you want people to show that you are an ignorant newbie.
Locking a java.util.concurrent style is more efficient than using synchronized blocks due to its explicit lock () and unlock () methods. For example, one way to lock a lock and another way to unlock it. This can lead to code that is hard to understand, and I would not do it if I didn’t have a very good reason, but sometimes there are good reasons.
james large
source share