Static versus non-static lock object in sychronized block
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 that 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 question 8774442, but it's not clear enough
what the different usage scenarios are.
No comments:
Post a Comment