Atomic 操作简单介绍
Java从JDK1.5开始提供了java.util.concurrent.atomic包,方便程序员在多线程环境下,无锁的进行原子操作。学习并发编程的时候,也借机去了解了一下Atomic包的内容。本文不太深入去解释各个类的作用,因为大部分都是差不多的,主要以AtomicInteger作为示例。
包路径java.util.concurrent.atomic
在并发的状态下,如果有多个线程都对一个同一个变量进行操作,有一些操作会被覆盖,从而使得我们得到不正确的结果,这里将会以一个整形静态数值累计增加10w次,并分别用两个线程来调用,观察结果。
并发下错误的结果
public class InnerAdd implements Runnable{
static int val = 0;
@Override
public void run() {
for (int i = 0; i < 100000 ; i++){
val++;
}
}
public void printAiVal(){
System.out.println(val);
}
}
public static void main(String[] args) throws InterruptedException {
InnerAdd ina = new InnerAdd();
// 线程t1
Thread t1 = new Thread(ina);
// 线程t2
Thread t2 = new Thread(ina);
// t1 和 t2 都进入到start状态,等待cpu调用
t1.start();
t2.start();
// 等待t1和t2都执行完毕
t1.join();
t2.join();
// 调用打印获取最后的结果
ina.printAiVal();
}
多次运行代码,始终得不到结果为20w的样本。大都在10-15w之间浮动(可见问题之大)
使用AtomicInteger进行操作
我们对InnerAdd进行部分修改,使得他使用atomic包提供的atomicInteger类里面的方法进行并发下,多个线程对同一个数值进行操作。
public class InnerAdd implements Runnable{
static AtomicInteger ai = new AtomicInteger(0);
@Override
public void run() {
for (int i = 0; i < 100000 ; i++){
ai.incrementAndGet(); // 等价++1
}
}
public void printAiVal(){
System.out.println(ai.get());
}
}
经过反复的运行,始终能得到正确结果20w,同时我们也去看一看这类提供了什么方法
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
public AtomicInteger() {
}
/**
* Gets the current value.
*
* @return the current value
*/
public final int get() {
return value;
}
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(int newValue) {
value = newValue;
}
/**
* Eventually sets to the given value.
*
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* <p><a href="package-summary.html#weakCompareAndSet">May fail
* spuriously and does not provide ordering guarantees</a>, so is
* only rarely an appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, valueOffset, -1);
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final int getAndAdd(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}
/**
* Atomically updates the current value with the results of
* applying the given function, returning the previous value. The
* function should be side-effect-free, since it may be re-applied
* when attempted updates fail due to contention among threads.
*
* @param updateFunction a side-effect-free function
* @return the previous value
* @since 1.8
*/
public final int getAndUpdate(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return prev;
}
/**
* Atomically updates the current value with the results of
* applying the given function, returning the updated value. The
* function should be side-effect-free, since it may be re-applied
* when attempted updates fail due to contention among threads.
*
* @param updateFunction a side-effect-free function
* @return the updated value
* @since 1.8
*/
public final int updateAndGet(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return next;
}
/**
* Atomically updates the current value with the results of
* applying the given function to the current and given values,
* returning the previous value. The function should be
* side-effect-free, since it may be re-applied when attempted
* updates fail due to contention among threads. The function
* is applied with the current value as its first argument,
* and the given update as the second argument.
*
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the previous value
* @since 1.8
*/
public final int getAndAccumulate(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}
/**
* Atomically updates the current value with the results of
* applying the given function to the current and given values,
* returning the updated value. The function should be
* side-effect-free, since it may be re-applied when attempted
* updates fail due to contention among threads. The function
* is applied with the current value as its first argument,
* and the given update as the second argument.
*
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the updated value
* @since 1.8
*/
public final int accumulateAndGet(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return next;
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value
*/
public String toString() {
return Integer.toString(get());
}
/**
* Returns the value of this {@code AtomicInteger} as an {@code int}.
*/
public int intValue() {
return get();
}
/**
* Returns the value of this {@code AtomicInteger} as a {@code long}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public long longValue() {
return (long)get();
}
/**
* Returns the value of this {@code AtomicInteger} as a {@code float}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public float floatValue() {
return (float)get();
}
/**
* Returns the value of this {@code AtomicInteger} as a {@code double}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public double doubleValue() {
return (double)get();
}
}
简单介绍AtomicInteger
在这个类中,首先去实现了序列化的接口,同时去获取了一个Unsafe的实例(感兴趣的可以去百度一下这个类,之类只做简单的介绍),先来看看Unsafe做了啥。
这里去判断虚拟机(JVM)加载了这个类没有,根据判断结果抛出Security异常或者返回一个Unsafe的操作类。 通过Unsafe类,我们可以对内存进行管理,多线程同步,线程的挂起和恢复等各种操作。
由于Unsafe的不少方法中必须提供原始地址(内存地址)和被替换对象的地址,偏移量要自己计算,一旦出现问题就是JVM崩溃级别的异常,会导致整个JVM实例崩溃,表现为应用程序直接crash掉。所以我们自己尽量不要去操作,我们这里用的atomic是官方提供的,所以理论上他们自己封装好了。我们只需要使用方法而不用关系线程同步的细节。
// 带参数的构造方法
public AtomicInteger(int initialValue) {
value = initialValue;
}
//不带参数的构造方法
public AtomicInteger() {
}
// 获取当前变量数值
public final int get() {
return value;
}
// 给变量设置一个值
public final void set(int newValue) {
value = newValue;
}
// lazySet是使用Unsafe.putOrderedObject方法,这个方法在对低延迟代码是很有用的,
// 它能够实现非堵塞的写入,这些写入不会被Java的JIT重新排序指令
// lazySet不保证写完之后对其他线程可见
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
// 先获取值,再设置一个新的值进去。 (得到旧值的同时赋了一个新的值)
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
//以原子的方式更新这个更新器所管理的对象(obj)的成员变量,并且将这个成员变量更新为给定的更新后的值(update)如果当前值等于期望值(expect)时。
// expect - 当前值 update - 期望值 , 成功执行后返回期望值
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
// weakCompareAndSet底层不会创建任何happen-before的保证, 也就是不会对volatile字段操作的前后加入内存屏障。
// 因此就无法保证多线程操作下对除了weakCompareAndSet操作的目标变量(该目标变量一定是一个volatile变量)之外其他的变量读取和写入数据的正确性。
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
// 先获取再增加1,等同i++
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
// 同理 i--
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, valueOffset, -1);
}
// 先获取再增加,自定义累加值
public final int getAndAdd(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}
// 先增加再获取,自定累加值
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}
// 先增加再返回 等同++i;
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
// --i
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
// 使用应用给定函数的结果自动更新当前值,并返回先前的值
public final int getAndUpdate(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return prev;
}
// 使用应用给定函数的结果自动更新当前值,并当前的值
public final int updateAndGet(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return next;
}
// 使用将给定函数应用于当前值和给定值的结果自动更新当前值,并返回先前的值
public final int getAndAccumulate(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}
// 使用将给定函数应用于当前值和给定值的结果自动更新当前值,并返回当前的值
public final int accumulateAndGet(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return next;
}