Java static variable updates
Solution 1
According to the JLS:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized
So this answers your first question. i.e.e exactly when the class is loaded :)
As per second question, nope. if the variable is declared private. Then the only access is via the method because of encapsulation.
Static variables lasts till the JVM is shutdown.
Solution 2
A static variable will be re-initialized when you restart the application.
Solution 3
counter
is not a private variable. So it is possible that this value is changed by some other class.
This variable will get reset whenever your program (or specifically the container/jvm) is restated.
jQguru
Updated on June 04, 2022Comments
-
jQguru almost 2 years
Below you can see a static variable
counter
in a Java class.The question is when will this variable reset? For example, when I restart the program, computer. What are the other possible scenarios it can reset?
Another question is: what could be the reasons for this variable to increase by less than the number of times the function do() is executed? For example, could it be something with starting multiple processes of the class
java Whatever
? Or could it be something with multiple threads/servers, etc?class Whatever { static int counter = 0; function do() { counter++; //... } }
Additional question: If multiple threads execute function do(), how will the counter variable behave? It will be less than the number of times function do() was executed?
-
jQguru over 11 yearsIf multiple threads access it, how will the counter variable bahave? It will be less than the number of times function do() was executed?
-
SJuan76 over 11 yearsYes. Think of
counter
being 2;thread1
does the operation, to calculate the ++ retrieves the 2 and adds 3, but before replacing the 2 with 3thread2
begins the operation, retrieves thatcounter
is still 2, and calculates the result as 3. In the end both threads will set the value ofcounter
to 3, while one of them should have set it to 4. It is called Concurrency or run condition.