5

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?

3
  • static variables are initialized only once, at the start of the execution of the program. Commented Nov 22, 2012 at 11:10
  • your counter is package private, so any class in the same package can assign an arbitrary value to it. Commented Nov 22, 2012 at 11:12
  • BTW, do is a reserved keyword and can not be used as a method name. Commented Nov 22, 2012 at 11:17

7 Answers 7

2

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

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

Comments

2

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.

Comments

1

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.

Comments

0

1) The variable is set(reset) when the class is loaded. Apart from shutting down the JVM, some servers load the class in different applications (v.g., the Tomcat webapps) and some of them allow restarting them.

2) Concurrent modification by threads. But it should be rare, unless you use it a lot. Use synchronized for the function/block.

2 Comments

If multiple threads access it, how will the counter variable bahave? It will be less than the number of times function do() was executed?
Yes. Think of counter being 2; thread1 does the operation, to calculate the ++ retrieves the 2 and adds 3, but before replacing the 2 with 3 thread2 begins the operation, retrieves that counter is still 2, and calculates the result as 3. In the end both threads will set the value of counter to 3, while one of them should have set it to 4. It is called Concurrency or run condition.
0

The question is when will this variable reset?

static variable can be reset using custom reset() method. If You say restart program, theoretically that variable will be initialized to it's value not reinitialized as it is not same(you restart program).

Comments

0
class Foo { // in same package
public static void main(String[] args) {
    Whatever w = new Whatever();
    for (int i = 0; i < 1000; i++) {
        w.do();
    }
    Whatever.counter = -1;
}

here do() is invoked 1000 times, but counter will have value at the end.

I used do() like you in your example, but note that is not a valid method name, because it's the keyword for a do while loop.

Comments

0

A static variable means that there are only one incarnation of that field during a program execution. It is loaded when the class is initialized.

For your second question, your variable isn't thread safe because multiple threads can access it at the same time. Even if your counter was volatile you would still face concurrency problem. You have three options, given your example and requirements:

If your only requirement is to manipulate the variable and the rest of the code won't depend of that you can use synchronize (killing a fly with a cannon) or AtomicInteger (the choice with better performance):

static synchronize int counter = 0;
// or
static AtomicInteger counter = new AtomicInteger();

If the rest of your code is dependent of your counter, you must use a lock object or synchronize your method:

class Whatever {

    static int counter = 0;

    synchronize function do() {
        counter++;
        if(counter < 10){
            //  do something
        }
    }
}

//  or

class Whatever {

    static int counter = 0;
    static final Object _lock = new Object();

    function do() {
        synchronized (_lock) {
            counter++;
            if(counter < 10){
                //  do something
            }
        }
    }
}

This are the options that are in my head right now, but probably there are more.

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.