4

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){
        ...
        }
    }
}
Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
  • 1
    http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html - also locking on a public variable is a bad idea and on a String literal an even worse idea. – assylias Aug 13 '13 at 10:11
  • 1
    You don't synchronize on a variable, you synchronize on an object so it doesn't matter if it is `static` or not. – Peter Lawrey Aug 13 '13 at 10:29
  • It means you cannot call `doSomething()` concurrently.. – boxed__l Aug 13 '13 at 10:35
  • See also https://stackoverflow.com/questions/133988/synchronizing-on-string-objects-in-java – Raedwald Aug 16 '18 at 10:27

2 Answers2

5

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0
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.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289