Volatile Fields

 

1)有时,对于只是读写一两个实例数据成员就使用synchronization看起来代价有些过大。如果不使用,又能怎么样呢。不幸地是对于现代的多处理器的机器或者当代的编译器,有太多错误的可能:

   多处理器的机器可以把内存变量临时存放在寄存器或者本地线程缓存中,结果,在不同处理器中运行的线程可能会对于同一个内存地址却看到不同的值。

 

   编译器可以整理代码以提高效率,编译器不会改变代码的含义,但是他们会假设同存中的值会被改变当且仅当他们会明确地在代码中被改变。然而,这些值可能会被其他线程改变,这样就产生了问题

2) Compilers are required to respect locks by flushing local caches as

 

necessary and not inappropriately reordering instructions

 详见 the Java Memory Model and Thread Specification developed by JSR 133

3)使用AtomicBoolean

   There are a number of wrapper classes in the java.util.concurrent.atomic

package for atomic integers, floating point numbers, arrays, and so on. These classes are

intended for systems programmers who produce concurrency utilities, not for the appli-

cation programmer.

4)在java 5.0以前,volatile 的语义是非常宽松的,语言的设计者们试着去给(虚拟机?)实现者们更大的自由来提高使用volatile fields的代码的性能。但是,过去的java specification是如此的复杂以致于实现者们并不总是去遵守它,这导致产生了另人迷惑的,不确定的行为。

例如 immutable objects 表现为并不是真的"不变"

Prior to Java SE 5.0, the semantics of volatile were rather permissive. The lan-

guage designers attempted to give implementors leeway in optimizing the performance of

code that uses volatile fields. However, the old specification was so complex that implemen

tors didn’t always follow it, and it allowed confusing and undesirable behavior, such as

immutable objects that weren’t truly immutable. 

5)

In summary, concurrent access to a field is safe in these three conditions:

• The field is final, and it is accessed after the constructor has completed.

• Every access to the field is protected by a common lock.

• The field is volatile.

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值