Trying to visualize and understand synchronization.
- What are the differences between using a static lock object (code A) and a non-static lock object (code B) for a synchronized block?
- How does it differ in practical applications?
- What are the pitfalls one would have that the other wouldn't?
- What are the criteria to determine which one to use?
Code A
public class MyClass1 {
private static final Object lock = new Object();
public MyClass1() {
//unsync
synchronized(lock) {
//sync
}
//unsync
}
}
Code B
public class MyClass2 {
private final Object lock = new Object();
public MyClass2() {
//unsync
synchronized(lock) {
//sync
}
//unsync
}
}
Note
The above code shows constructors, but you could talk about how the behavior is different in a static method and a non-static method too. Also, would it be advantageous to use a static lock when the synchronized block is modifying a static member variable?
I already looked at answers in this question, but it's not clear enough what the different usage scenarios are.
private final Object lock = "niceLiteralString";
. – Sokotrasynchronized (a){}; synchronized(b){}; synchronized(c){}
could all end up using the same lock. They can also throw NullPointerExceptions, if that field is null. – Sokotra