一个对象是否总是看到其最新的内部状态而与线程无关? [英] Does an object always see its latest internal state irrespective of thread?
问题描述
比方说,我有一个带有简单整数计数变量的可运行对象,该变量在每次可运行对象运行时都会增加.该对象的一个实例被提交以在计划的执行程序服务中定期运行.
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 a scheduled executor service.
class Counter implements Runnable {
private int count = 0;
@Override
public void run() {
count++;
}
}
Counter counter = new Counter();
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);
在这里,对象正在访问不同线程内部的内部状态(读取和递增).这段代码是线程安全的吗?或者在另一个线程中调度count
变量时,我们是否有可能丢失对它的更新?
Here, the object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread-safe or is it possible that we lose updates to the count
variable when it's scheduled in a different thread?
推荐答案
对象是否总是看到其最新内部状态而与线程无关?
仅出于本问题及其答案的目的,一个对象什么都不做.这只是记忆.线程是执行实体.说有物体看见任何东西是一种误导.正是线程正在查看/读取对象状态.
Just to be clear for the purposes of this question and its answers, an object doesn't do anything; it's just memory. Threads are the executing entity. It's misleading to say does an object see whatever. It's the thread that's doing the seeing/reading of object state.
这不是在Javadoc中指定的,但是
This isn't specified in the javadoc, but
Executors.newScheduledThreadPool(5);
返回一个ScheduledThreadPoolExecutor
.
您的代码正在使用
executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);
The javadoc for ScheduledThreadPoolExecutor#scheduledWithFixedDelay
states
提交一个周期性操作,该操作在给定后首先启用 初始延迟,然后在给定的延迟之间 终止一个执行并开始执行下一个.
Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.