Consider the following code:
public class Foo {
private static final Object LOCK = new Object();
private Object _lockRef1 = LOCK;
private Object _lockRef2 = LOCK;
private int _indx = 0;
public void dec() {
synchronized(_lockRef1) {
_indx--;
}
}
public void inc() {
synchronized(_lockRef2) {
_indx++;
}
}
}
Is call to methods dec()
and inc()
threadsafe? On the one hand these methods are synchronized on two different instances _lockRef1
and _lockRef2
. On the other hand, these instances "point" on the same object LOCK
...
Synchronization is usually needed when you are sharing data between multiple invocations and there is a possibility that the data would be modified resulting in inconsistency. If the data is read-only then you dont need to synchronize. In the code snippet above, there is no data that is being shared.
In other words, the synchronized method increases the waiting time, whereas synchronized block has an advantage over the method as its scope is limited and smaller than the method.
Only one thread per instance can execute inside a synchronized instance method.
They're not "synchronized on two different instances" - just because you use two different variables doesn't mean there are two different instances. You've got several variables each of which will have the same value - a reference to the single instance of java.lang.Object
.
So yes, this is thread-safe. Of course you shouldn't write code like this in terms of readability, but assuming you're just trying to understand what happens, it's fine.
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