1
votes

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.

1
Post some code, please :) - An SO User
not clear. post and example. a synchronized method uses the class object as a lock. - njzk2
@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
@jameslarge: yes, that was not entirely clear to me, thanks for explaining - njzk2

1 Answers

1
votes

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);
        }
    }
}