2

I have a question regarding Java concurrency. If I synchronize a critical section based on an object, what is difference between declaring that variable as a final static Object versus simply final Object.

I understand that the static keyword defines a variable as belonging to the class, but I'm a little hazy on its meaning in a multi-threaded environment.

Please refer to the code sample below. Currently I have the lock object declared as private final Object lock = new Object(), what will be the difference if I add the static keyword?

class ConcurrencySample {
    private String message = null;
    private final Object lock = new Object();
    //private final static Object lock = new Object();

    public void setMessage(String msg) {
        synchronized (lock) {
            message = msg;
        }
    }
    public String getMessage() {
        synchronized (lock) {
            String temp = message;
            message = null;
            return temp;
        }
    } 
}

Thanks for the help!

BlueBucket7
  • 185
  • 3
  • 13
  • 2
    It has no special meaning, just what you already said. If you declare your `lock` to be `static`, it will be shared by all instances of the class, therefore a `setMessage()/getMessage()` call on any instance will block all other instances. Seeing as the `message` field you manipulate isn't `static`, there's no reason why the lock should be `static` either. – biziclop Jul 07 '15 at 18:35

2 Answers2

6

If you declare the object as static final, then there is exactly one lock shared across all instances of the class. That means that if two independent instances each try to synchronize on it, only one of the two instances will be able to get the lock at a time.

If you declare the object as final, then there is one copy of the lock per instance of the class, so if two independent instances of the class each try to acquire the lock, they're each acquiring their own locks, so there's no blocking involved. However, if multiple threads all invoke methods on one instance of the class concurrently, those threads will try to acquire the same object, so only one thread can proceed at a time.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
2

Making the lock variable static will make any thread that reads or writes a message against any instance of ConcurrencySample block, as opposed to blocking only on a specific instance that is being read by another thread.

It will basically decrease the concurrency level of your application: Only one thread can read or write a message on any instance, even if other threads want to affect a completely different instance.

M A
  • 71,713
  • 13
  • 134
  • 174