I ran into this logic that someone had implemented at work today and it just feels wrong to be creating locks this way. Do you guys have a better solution for this ? The problem with not using synchronized block on myObj is that it can be null. Any other suggestions ??
public class myClass {
private Object myObj;
private Object lock = new Object();
public void method1() {
synchronized( lock ) {
// has logic to read myObj
}
}
public void method2() {
synchronized( lock ) {
// has logic to update myObj
}
}
}
The lock() method is one of the most important methods of the Lock interface. It is used for acquiring the lock. For thread scheduling purposes, the current thread becomes disabled when the lock is not available. The lock() method is a public method that returns void.
The tool needed to prevent these errors is synchronization. In synchronization, there are two types of locks on threads: Object-level lock: Every object in java has a unique lock.
Looks appropriate to me. I'd also add final
to the lock declaration to make sure it doesn't inadvertently get changed:
private final Object lock = new Object();
It's appropriate. Another way, while it is hotly debated whether it is proper, is to synchronize this
if you want to lock.
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