Java实例变量可见性(ThreadLocal)
在类中 ReentrantReadWriteLock 是以下好奇的评论:
transient ThreadLocalHoldCounter readHolds;
Sync() {
readHolds = new ThreadLocalHoldCounter();
setState(getState()); // ensures visibility of readHolds
}
“确保可见性”是什么意思?我问的原因是我遇到了一种情况,看起来线程本地 readHolds 正在被重置(线程本地被实现为 WeakReferences,因此只要包含的 Sync 对象仍然存在,就不会发生这种情况)。 setState/getState 只是更改另一个实例变量并且不触及 readHolds。
In the class ReentrantReadWriteLock is the following curious comment:
transient ThreadLocalHoldCounter readHolds;
Sync() {
readHolds = new ThreadLocalHoldCounter();
setState(getState()); // ensures visibility of readHolds
}
what does it mean by "ensures visibility"? The reason I ask is that I have a situation where it looks as though the thread local readHolds is being reset (thread locals are implemented as WeakReferences so that shouldn't happen as long as the containing Sync object is still alive). setState/getState simply alter another instance variable and don't touch readHolds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
setState(int)
方法执行对易失性变量的赋值。这会导致当前线程执行的任何分配(包括 readHolds)被刷新到“主内存”。其他调用
getState()
的线程读取这个相同的易失性变量。由于变量是易失性的,因此线程的缓存首先被清除,强制后续的读取操作转到主内存,在那里它们将找到readHolds
的最新值。The
setState(int)
method performs an assignment to a volatile variable. This causes any assignments performed by the current thread—including readHolds—to be flushed to "main memory".Other threads calling
getState()
read this same volatile variable. Since the variable is volatile, the thread's cache is cleared first, forcing subsequent read operations to go out to main memory, where they will find the most recent value ofreadHolds
.