Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static variable updates

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?

like image 629
jQguru Avatar asked Nov 22 '12 11:11

jQguru


2 Answers

A static variable will be re-initialized when you restart the application.

like image 130
Philipp Avatar answered Sep 29 '22 06:09

Philipp


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.

like image 36
Jatin Avatar answered Sep 29 '22 06:09

Jatin