What is the effect of having a synchronized using a static variable?
public class Something {
public static final String LOCK = "lala";
public void doSomething(){
synchronized(LOCK){
...
}
}
}
What is the effect of having a synchronized using a static variable?
public class Something {
public static final String LOCK = "lala";
public void doSomething(){
synchronized(LOCK){
...
}
}
}
Only one thread will be able to invoke doSomething()
at a time, whatever the Something
instance is, since the same lock is shared by all the instances.
To be complete, I'll repeat the comment from @assylias here: don't synchronize on public variables, and don't synchronize on String literals, which are shared even if private due to the String pool. You don't want any other unrelated class to synchronize on the same lock, introducing side effects like deadlocks by doing so.
public static final String LOCK = "lala";
public void doSomething(){
synchronized(LOCK){
...
}
}
Lock obtained by the thread before entering the synchronized block will be a class level lock rather than an object level lock.