CAS(Compare And Swap)、AtomicStampedReference、AtomicReference
AtomicInteger.incrementAndGet
AtomicInteger
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
Unsafe
public final int getAndAddInt(Object obj, long valueOffset, int i) {
int current;
do {
current = this.getIntVolatile(obj, valueOffset);
} while(!this.compareAndSwapInt(obj, valueOffset, current, current + i));
return current;
}
public native int getIntVolatile(Object var1, long var2);
public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);
CAS缺点
1、如果一直没成功,一直循环,给CPU带来很大开销
2、ABA问题。一个变量读取值是A,恰巧另一个线程把它换成了B然后又换回了A,这时候读取的还是A,实际是改变了值的。Java提供了AtomicStampedReference
来解决,原理是添加一个额外的版本来做判断。
AtomicStampedReference-Demo
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;
/**
* ABA问题
* @author admin
*/
public class AtomicStampedReferenceDemo {
public static void main(String[] args) {
AtomicStampedReference<Integer> atomic = new AtomicStampedReference<>(100, 0);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
// 线程A 100 -> 101, 等待线程B执行完 100 -> 101 -> 100
threadPoolExecutor.execute(() -> {
int beginStamp = atomic.getStamp();
System.out.println("begin stamp = " + beginStamp);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end stamp = " + atomic.getStamp());
boolean r3 = atomic.compareAndSet(100, 101, beginStamp, beginStamp + 1);
System.out.println("r3 = " + r3);
});
// 线程B 100 -> 101 -> 100
threadPoolExecutor.execute(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("stamp = " + atomic.getStamp());
boolean r1 = atomic.compareAndSet(100, 101, atomic.getStamp(), atomic.getStamp() + 1);
System.out.println("r1 = " + r1);
System.out.println("stamp = " + atomic.getStamp());
boolean r2 = atomic.compareAndSet(101, 100, atomic.getStamp(), atomic.getStamp() + 1);
System.out.println("r2 = " + r2);
});
threadPoolExecutor.shutdown();
/**
* begin stamp = 0
* stamp = 0
* r1 = true
* stamp = 1
* r2 = true
* end stamp = 2
* r3 = false
*/
}
}
3、只能保证一个共享变量的原子操作。注:从Java 1.5开始,JDK提供了AtomicReference
类来保证引用对象之前的原子性,可以把多个变量放在一个对象里来进行CAS操作。
AtomicReference-Demo
package com.kornzhou.javademo.concurrentprogramming.lock;
import java.util.concurrent.atomic.AtomicReference;
/**
* <ul>
* <li>AtomicReference也是java.util.concurrent包下的类,</li>
* <li>跟AtomicInteger等是一样的,也是基于CAS无锁理论实现的,</li>
* <li>但是不同的是 AtomicReference 是操控多个属性的原子性的并发类</li>
* </ul>
*
* @author admin
*/
public class AtomicReferenceDemo {
public static void main(String[] args) {
Person old = new Person("old", 100);
AtomicReference<Person> atomicReference = new AtomicReference(old);
new Thread(() -> {
compareAndSet(old, atomicReference);
}, "线程A-").start();
new Thread(() -> {
compareAndSet(old, atomicReference);
}, "线程B-").start();
try {
Thread.sleep(1000);
System.out.println(atomicReference.get().toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
final int ii = i;
new Thread(() -> {
// CAS无锁并发,getAndSet返回值都不一样
Person test1 = atomicReference.getAndSet(new Person("test" + ii, 10 * ii));
System.out.println("test" + ii + " = " + test1.toString());
}).start();
}
try {
Thread.sleep(2000);
System.out.println(atomicReference.get().toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 线程A-setSuc = true
* 线程B-setSuc = false
* [name: test, age: 0]
* test0 = [name: test, age: 0]
* test1 = [name: test0, age: 0]
* test2 = [name: test1, age: 10]
* test4 = [name: test2, age: 20]
* test5 = [name: test4, age: 40]
* test6 = [name: test5, age: 50]
* test7 = [name: test6, age: 60]
* test8 = [name: test7, age: 70]
* test9 = [name: test8, age: 80]
* test3 = [name: test9, age: 90]
* [name: test3, age: 30]
* Disconnected from the target VM, address: '127.0.0.1:56767', transport: 'socket'
*
* Process finished with exit code 0
*/
}
private static void compareAndSet(Person old, AtomicReference<Person> atomicReference) {
// CAS
boolean setSuc = atomicReference.compareAndSet(old, new Person("test", 0));
System.out.println(Thread.currentThread().getName() + "setSuc = " + setSuc);
}
static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "[name: " + this.name + ", age: " + this.age + "]";
}
}
}
乐观锁
CAS是乐观锁