Search code examples
javamultithreadingtimertask

Does everything scoped within TimerTask need to be thread safe?


Does everything scoped within TimerTask need to be thread safe?

Example

@Autowired
private MySweetService mySweetService;
int delaySeconds = 0;
int intervalMinutes = 1;    

for(int i=0; i<5; i++) {
    Timer timer = new Timer();

    timer.schedule(new TimerTask() {
        public void run() {
            // This method below is my questionable area
            mySweetService.doStuff(i);
        }
    }, delaySeconds, intervalMinutes);
}

Does everything need to be thread safe within the timerTask anonymous class? Any inherent problem?


Solution

  • No. For every Timer there is one thread. The timer will execute only one task at one time. See Timer

    Thus the mySweetService.doStuff method does not need to be thread-safe.

    Edit: The question was modified. Originally only one Timer instance was created outside the loop, thus there was only one thread. Now it creates theTimers in the loop; the above does no longer hold: Each Timer will have its own thread and race-conditions can occur. This is pretty much equivalent to using Thread or Runnable.