Does an object always see its latest internal state irrespective of thread?

前端 未结 3 1969
旧巷少年郎
旧巷少年郎 2021-02-20 00:15

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

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 01:03

    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.

提交回复
热议问题