Is static variables are Thread specific in java?
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开发者_Go百科 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.
No, use ThreadLocal for that.
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.
No, They are loaded class specific
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...
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.
精彩评论