1

Suppose I have a class having static member variable.There are two synchronized methods,static and instance, present in that class and both the methods are trying to modify the value of static member variable. First thread is having lock on object of that class , so first thread can access both static synchronized and instance synchronized method. Second thread is having class level lock , so it can access only static synchronized method. In this scenario , how to achieve thread safety.

jasminum
  • 471
  • 1
  • 7
  • 12
  • Post some code, please :) – An SO User May 30 '14 at 17:53
  • not clear. post and example. a synchronized method uses the class object as a lock. – njzk2 May 30 '14 at 17:53
  • Read more [How to synchronize a static variable among threads running different instances of a class in java?](http://stackoverflow.com/questions/2120248/how-to-synchronize-a-static-variable-among-threads-running-different-instances-o?rq=1) – Braj May 30 '14 at 17:56
  • @njzk2 a _static_ synchronized method uses the class object as a lock, but jasminum was asking how to insure that static data can be safely accessed from an _instance_ method. – Solomon Slow May 30 '14 at 19:16
  • @jameslarge: yes, that was not entirely clear to me, thanks for explaining – njzk2 May 30 '14 at 19:37

1 Answers1

1

Either add an additional synchronized block to the instance method, that synchronized on the class object, or use an additional lock object. The following listing shows the former:

class Foo {
    private static Set<String> state = new HashSet<>();
    public static synchronized void bar(String item) {
        state.add(item);
    }
    public /* synchronized */ baz(String item) {
        synchronized (Foo.class) {
            state.add(item);
        }
    }
}
nosid
  • 48,932
  • 13
  • 112
  • 139
  • additional lock object means something similar to this : private static final Object lock= new Object(). Can we make that static variable,state, as volatile and no need to mention synchronized keyword? – jasminum May 30 '14 at 18:04
  • @jasminum: It depends on the type and the operations, if you can use `volatile` or an atomic type instead of `synchronized`. You have to provide more information in this case. – nosid May 30 '14 at 18:08
  • @jasminum, `volatile` is not a substitute for `synchronized`. The _main_ purpose of `synchronized` is to prevent two or more threads from operating on the same data at the same time. The secondary purpose is to insure that changes made by one thread will be promptly seen by other threads. That's _all_ that `volatile` does, and it's not enough to guarantee safety in most cases. – Solomon Slow May 30 '14 at 19:14