/ Java  

Java Multithreading 13: AtomicIntegerFieldUpdater

AtomicIntegerFieldUpdater, AtomicLongFieldUpdater, and AtomicReferenceFieldUpdater are similar in principle and usage.

AtomicIntegerFieldUpdater introduction and function list

AtomicIntegerFieldUpdater can perform atomic update on the specified member of type volatile int. It is based on reflection.

AtomicIntegerFieldUpdater function list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Atomically adds the given value to the current value of the field of the given object managed by this updater.
public int addAndGet(T obj, int delta) {

// Atomically sets the field of the given object managed by this updater to the given updated value if the current value {@code ==} the expected value.
public abstract boolean compareAndSet(T obj, int expect, int update);

// Atomically decrements by one the current value of the field of the given object managed by this updater.
public int decrementAndGet(T obj)

// Returns the current value held in the field of the given object managed by this updater.
public abstract int get(T obj);

// Atomically sets the field of the given object managed by this updater to the given value and returns the old value.
public int getAndSet(T obj, int newValue)

// Atomically increments by one the current value of the field of the given object managed by this updater.
public int incrementAndGet(T obj)

// Eventually sets the field of the given object managed by this updater to the given updated value.
public abstract void lazySet(T obj, int newValue)

// Creates and returns an updater for objects with the given field.
public static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)

// Sets the field of the given object managed by this updater to the given updated value
public abstract void set(T obj, int newValue)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class IntFieldTest {
public static void main(String[] args) {
Class cls = Person.class;

// Create AtomicIntFieldUpdater object, parameter is "class object" and "int variable's name"
AtomicIntFieldUpdater mAtoInt = AtomicIntFieldUpdater.newUpdater(cls, "id");
Person person = new Person(12345);

// Compare person's id. If it's 12345, set to 1000
mAtoInt.compareAndSet(person, 12345, 1000);
System.out.println("id = " + person.getId());
}
}

class Person {
volatile int id;

public Person(int id) {
this.id = id;
}

public void setId(int id) {
this.id = id;
}

public int getId() {
return id;
}
}

Result:

1
id = 1000