2

Is static variables are Thread specific, means

class A { public static int i = 10; } Class B { A.i = 20; } Class C { A.i = 30; } Class D { System.out.println(A.i); } 

Above classes I am calling from my web application, i.e. in first request I Call Class B, in second request I call Class B and in third request I have called Class D. Now what it will print 10/20/30?

Thank You.

2
  • 4
    Your example code doesn't even compile. Please shows us compiling code. Commented May 12, 2011 at 12:14
  • 2
    I don't think compiling sample code is required. Its not unusual for people to post stripped down versions of their code. What's important is that your are able to get a good sense of what they are trying to do. Which in this case you can. Commented May 12, 2011 at 14:12

5 Answers 5

5

No, use ThreadLocal for that.

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

Comments

3

The correct answer to your question (will it print 10/20/30?), assuming that each request might be processed by a different thread, is "yes".

Logically, if each of those requests happen in chronological order, and each in a different thread, then you would see 20 (the value is not thread-specific, which I think you're asking), but note that even if the call to D happens chronologically last, it could still see the value '10'; the field is neither final nor volatile, so the Java Memory Model makes no guarantees about WHEN the change to 20 will be visible to other threads.

Comments

1

No, They are loaded class specific

Comments

1

static variable are global and shared across threads. this means that in your example (B -> C -> D) d will print 30 (only if they are called in that order

this has some issues for synchronization you might wanna be aware of...

Comments

0

Static variables are global that means you can make changes on them wherever you want and variable will has the final value that you assigned to it.In a method if the variable is private you make changes but out of the method that variable will has same value before the method's calculate.Eventually this code will show you 30.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.