1

Is it safe to say that a ThreadLocal variable is conceptually the 'opposite' of a volatile variable in Java? Because in the former, every thread will only read/updatea local copy of the variable. But in the latter, every thread will always see the latest value of the variable that is in main memory....no chance of seeing stale values.

4

1 回答 1

0

完全正确,但略有扭曲,

  • ThreadLocal 变量是每个线程不同的变量
  • 对于使用相同对象的每个线程来说,任何其他变量都只存在一次,无论它是否为易失性。

然而,Volatile 指定了某种线程读/写边界,因此它们必须在任何其他线程写入的最新值上同步。但是,使用 volatile 并不能确保线程安全。

例如,增加 volatile int 的 increment 方法可能仍会产生重复。为确保工作线程安全,您必须同步更新 volatile 属性的方法!

检查此以获取更多详细信息:https ://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html

于 2013-08-30T15:06:01.610 回答