Java Concurrency 简明教程

Java Concurrency - AtomicReference Class

java.util.concurrent.atomic.AtomicReference 类提供对基础对象引用的操作,该引用可被原子性地读写,并且还包含高级原子操作。AtomicReference 支持对基础对象引用变量的原子操作。它有类似对 volatile 变量的读写操作的 get 和 set 方法。也就是说,set 操作与任何对相同变量的后续 get 操作之间存在先行发生关系。原子 compareAndSet 方法也有这些内存一致性特征。

A java.util.concurrent.atomic.AtomicReference class provides operations on underlying object reference that can be read and written atomically, and also contains advanced atomic operations. AtomicReference supports atomic operations on underlying object reference variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

AtomicReference Methods

以下是 AtomicReference 类中可用的重要方法列表。

Following is the list of important methods available in the AtomicReference class.

Sr.No.

Method & Description

1

public boolean compareAndSet(V expect, V update) Atomically sets the value to the given updated value if the current value == the expected value.

2

public boolean get() Returns the current value.

3

public boolean getAndSet(V newValue) Atomically sets to the given value and returns the previous value.

4

public void lazySet(V newValue) Eventually sets to the given value.

5

public void set(V newValue) Unconditionally sets to the given value.

6

public String toString() Returns the String representation of the current value.

7

public boolean weakCompareAndSet(V expect, V update) Atomically sets the value to the given updated value if the current value == the expected value.

Example

以下 TestThread 程序显示了在基于线程的环境中使用 AtomicReference 变量。

The following TestThread program shows usage of AtomicReference variable in thread based environment.

import java.util.concurrent.atomic.AtomicReference;

public class TestThread {
   private static String message = "hello";
   private static AtomicReference<String> atomicReference;

   public static void main(final String[] arguments) throws InterruptedException {
      atomicReference = new AtomicReference<String>(message);

      new Thread("Thread 1") {

         public void run() {
            atomicReference.compareAndSet(message, "Thread 1");
            message = message.concat("-Thread 1!");
         };
      }.start();

      System.out.println("Message is: " + message);
      System.out.println("Atomic Reference of Message is: " + atomicReference.get());
   }
}

这将产生以下结果。

This will produce the following result.

Output

Message is: hello
Atomic Reference of Message is: Thread 1