0

My question is related to thread safety of static variables.

Class A{
private static int test=0;
public static void synchronized  m1(){
    test=test+1;
}
public void synchronized  m2(){
   test=test+1;
}

}

If two threads, t1 having static lock and t2 having object lock, can continue simultaneously, then how will state test of class A will be thread safe?

May be , I am missing something very basic, but not sure how it works.

Based on below answers, I get the impression that if such states have to be made thread safe, then either both locks should be held by a thread which is updating this state, or make sure it is being accessed by either only static methods or only non-static methods. right?

3
  • same question stackoverflow.com/questions/5443297/… Commented Nov 30, 2014 at 17:44
  • If you need only increment/decrement operation you can use some Atomic classes. For example in AtomicInteger this operations is thread safe (you need use specific method of object). Commented Nov 30, 2014 at 17:50
  • On that update: The important thing is that the object that guards the critical piece of code is always the same. That's what my answer does: makes both methods use the class as the monitor object. You can, when in need of more fine grained locking, also use other objects for synchronizing, and those can be either static or instance variables. The use determines what is the appropriate use - static when you need to synchronize across all instances, an instance object otherwise. I used the class as the monitor, as a thread safe handling of a static variable was needed. Commented Nov 30, 2014 at 18:47

2 Answers 2

5

This is not thread safe. The methods use different monitor objects: the static method uses the class, and the instance method synchronizes using the object instance. You can make the instance method use the class as the monitor object by:

synchronized (A.class) {
...

if you need to. I'd consider making both methods static though, unless you need to access instance variables.

Sign up to request clarification or add additional context in comments.

Comments

0

Its not thread-safe, and you (the question author) explained very well why.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.