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.