Denes Garda
Denes Garda

Reputation: 127

Updating static variables in a Timer Task

I have a simple Java timer set up, and I have a static boolean before it. Is there a way to update that boolean inside the timer?

I want to update the boolean named b that I declare in the first line inside of timerTask. b is static and cannot be changed inside of a timer task normally. Is there a way to get around this?

boolean b = false;
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        try {
            //update the value of b
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
};
timerTask.run();

Upvotes: 0

Views: 312

Answers (1)

Stefan Fenn
Stefan Fenn

Reputation: 483

You need a reference to update the value. An easy thread-save solution is the usage of AtomicBoolean as follows

import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

public class MyClass {
    public static void main(String args[]) {
        AtomicBoolean b = new AtomicBoolean();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println(b);
                b.set(true);
                System.out.println(b);
            }
        };
        timerTask.run();
    }
}

Upvotes: 2

Related Questions