Search code examples
javamultithreadingtimerthread-safetytimertask

Thread safe calling a TimerTask from within another Thread


I have a class ABC that implements runnable. There are multiple threads of the ABC running. In each thread I want to schedule a TimerTask. The function called within this TimerTask block needs to be thread safe with respect to the variables of the thread.

public class ABC implements Runnable {
private int abc = 0;

public void run() {

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            this.someFunc();
        }
    }, 1000, 1000);
    while (true) {
        abc = (abc + 1) % 20;
    }



}

void someFunc() {
    abc--;
}
}

Is this thread safe or do I need to make someFunc() a synchronized function?


Solution

  • The Javadoc says:

    public class Timer extends Object

    A facility for threads to schedule tasks for future execution in a background thread.

    Since it runs in a background thread, it's not thread safe.

    Whether or not someFunc() should be a synchronized function depends on what its doing, making it synchronized doesn't automatically guarantee thread safety.