Let\'s say I have a runnable with a simple integer count variable which is incremented every time runnable runs. One instance of this object is submitted to run periodically in
No, this code is not thread-safe because there isn't any happens-before relation between increments made in different threads started with ScheduledExecutorService
.
To fix it, you need to either mark the variable as volatile
or switch to AtomicInteger
or AtomicLong
.
UPDATE:
As @BoristheSpider mentioned, in general in case of increment/decrement making a variable volatile
is not enough since increment/decrement is not atomic itself and calling it from several threads concurrently will cause race conditions and missed updates. However, in this particular case scheduleWithFixedDelay()
guarantees (according to Javadoc) that there will be overlapping executions of scheduled task, so volatile
will also work in this particular case even with increment.