Atomic Access <译>
In programming, an atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn’t happen at all. No side effects of an atomic action are visible until the action is complete.
在编程领域,一个原子操作是一次有效发生的动作。一个原子操作不能在中间停下来:它要么发生,要么不发生。在原子操作完成之前,它产生的副作用不可预见。
We have already seen that an increment expression, such as c++, does not describe an atomic action. Even very simple expressions can define complex actions that can decompose into other actions. However, there are actions you can specify that are atomic:
我们已经见识过了一个增量表达式,例如:C++
,它不是一个原子操作。即使是非常简单的表达式也可以定义为可以分解为其他操作的复杂操作。但是,你可以指定一些原子操作:
- Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
对于引用变量和大多数基本变量(除long和double之外的所有基本类型),读取和写入都是原子的。 - Reads and writes are atomic for all variables declared volatile (including long and double variables).
对于声明为volatile
的所有变量(包括long和double变量),读取和写入都是原子的。
Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What’s more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
原子操作不能交错执行,所以使用原子操作不用担心线程干扰。然而,原子操作并不能消除synchronize的所有需要,因为内存一致性错误仍然是有可能的(是指原子操作不能取缔synchronize)。使用volatile变量可以减少内存一致性错误的风险,因为任何对volatile变量的读写都会与同一变量的后续建立happens-before
的关系。这就意味着对volatile变量的更改始终对其他线程可见。更重要的是,这也意味着当线程读取volatile变量时,它不仅能够看到对volatile变量的最新修改,还能预见到更改代码导致的副作用。
Using simple atomic variable access is more efficient than accessing these variables through synchronized code, but requires more care by the programmer to avoid memory consistency errors. Whether the extra effort is worthwhile depends on the size and complexity of the application.
使用简单的原子变量访问比通过synchronized代码更高效,但程序员需要更加小心去避免内存一致性错误。额外的努力是否值得,取决于程序的大小和复杂度。
Some of the classes in the java.util.concurrent package provide atomic methods that do not rely on synchronization. We’ll discuss them in the section on High Level Concurrency Objects.
java.util.concurrent
包中的某些类提供了不依赖于synchronization的原子方法。我们将会在高级并发编程对象中讨论它们。
评论