java:AtomicReference使用

java:AtomicReference使用

1 前言

AtomicReference源码可知,本质是使用CAS方法+自旋更新引用对象value(AtomicReference是泛型类,V value代表引用对象),如getAndUpdate、updateAndGet、getAndAccumulate、accumulateAndGet方法。因为CAS利用CPU指令保证了操作的原子性(更新安全可靠),达到了锁的效果,而自旋则是采用循环的方式尝试获取锁,当线程发现锁被占用,会循环判断锁状态,直至获取锁。在同样保证了线程安全的前提下,好处是减少了线程上下文切换的消耗(相比于阻塞式悲观锁synchronized提升了效率),缺点是循环比较耗费CPU。自旋锁是乐观锁中的一种,即认为线程更新值时不会出错,一旦别的线程更改了value,导致当前线程比较更新出错,则再次重新获取当前值,再做更新。

2 使用

源码可知,AtomicReference的引用对象为value,因为volatile修饰的原因,即便是不同线程,每次调用get()方法都会返回当前主内存中value变量的最新值(变量是存放在主内存中的),保证了线程间变量的可见性。

private static final long serialVersionUID = -1848883965231344442L;

private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;

static {
    try {
        valueOffset = unsafe.objectFieldOffset
            (AtomicReference.class.getDeclaredField("value"));
    } catch (Exception ex) { throw new Error(ex); }
}

private volatile V value;

/**
 * Creates a new AtomicReference with the given initial value.
 *
 * @param initialValue the initial value
 */
public AtomicReference(V initialValue) {
    value = initialValue;
}

/**
 * Creates a new AtomicReference with null initial value.
 */
public AtomicReference() {
}

/**
 * Gets the current value.
 *
 * @return the current value
 */
public final V get() {
    return value;
}

2.1 lazySet方法

AtomicReference的set方法形如setter方法,而lazySet效果一致,且使用unsafe实现,且value由volatile修饰(可见、禁止指令重排,但非原子性),使用unsafe.putOrderedObject(禁止指令重排,但不可见)进行set操作,两者常结合使用赋值:

public final void set(V newValue) {
        value = newValue;
    }
private volatile V value;

public final void lazySet(V newValue) {
    unsafe.putOrderedObject(this, valueOffset, newValue);
}

因为AtomicReference中value是volatile修饰的,故更新后会立马回写到主内存中:

@AllArgsConstructor
@ToString
@Getter
static class SU{
    String name;
    Boolean flag;
}

public static void lazySets(){
    AtomicReference<SU> ato = new AtomicReference<>();
    SU su = new SU("A",Boolean.FALSE);
    ato.set(su);
    long start = System.currentTimeMillis();
    AtomicLong ll = new AtomicLong();
    new Thread(()->{
        System.out.println("A线程开始");
        while (!ato.get().getFlag()){

        }
        System.out.println("A线程结束");
        ll.set(System.currentTimeMillis());
        System.out.println("总耗时:"+(ll.get()-start)+"ms");
    },"threadA").start();

    try {
        TimeUnit.SECONDS.sleep(6);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //6秒后设置标志位
    ato.lazySet(new SU("B",Boolean.TRUE));
}

执行结果:

A线程开始
A线程结束
总耗时:6063ms

2.2 compareAndSet和weakCompareAndSet方法

public final boolean compareAndSet(V expect, V update) {
    return unsafe.compareAndSwapObject(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(V expect, V update) {
    return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}

这两个方法本质都是调用unsafe.compareAndSwapObject,效果完全一致。compareAndSet主要是后续为getAndUpdate、updateAndGet、getAndAccumulate、accumulateAndGet方法充当自旋的锁的,因为unsafe.compareAndSwapObject(this, valueOffset, expect, update),实际就是获取this对象本身的偏移地址为valueOffset的对象,即value,然后如果原值为expect,则返回true,且更新值value为update,反之value的原值!=expect,则返回false,不做更新操作。

weakCompareAndSet之所以加上weak,是因为可能会失败(即返回false的情况),所以后续需要作为一个锁,通过自旋来达到线程安全的更新方式,故而compareAndSet、weakCompareAndSet不建议单独使用,应该采用与自旋方式结合使用。

2.3 getAndSet方法

unsafe.getAndSetObject,实际效果是,返回旧值,并直接更新为新值newValue,Unsafe工具类下一个方法,不过多赘述。

@SuppressWarnings("unchecked")
public final V getAndSet(V newValue) {
    return (V)unsafe.getAndSetObject(this, valueOffset, newValue);
}

2.4 getAndUpdate、updateAndGet、getAndAccumulate、accumulateAndGet方法

public final V getAndUpdate(UnaryOperator<V> updateFunction) {
    V prev, next;
    do {
        prev = get();
        next = updateFunction.apply(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 V updateAndGet(UnaryOperator<V> updateFunction) {
    V prev, next;
    do {
        prev = get();
        next = updateFunction.apply(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 V getAndAccumulate(V x,
                                BinaryOperator<V> accumulatorFunction) {
    V prev, next;
    do {
        prev = get();
        next = accumulatorFunction.apply(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 V accumulateAndGet(V x,
                                BinaryOperator<V> accumulatorFunction) {
    V prev, next;
    do {
        prev = get();
        next = accumulatorFunction.apply(prev, x);
    } while (!compareAndSet(prev, next));
    return next;
}

getAndUpdate和updateAndGet,getAndAccumulate和accumulateAndGet,源码可知本质就是返回旧值prev,或者更新后的新值next的区别,UnaryOperator和BinaryOperator,区别就是一元和二元参数,演示如下:

package com.xiaoxu.test;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BinaryOperator;
import java.util.function.UnaryOperator;

/**
 * @author xiaoxu
 * @date 2022-10-21
 * spring_boot:com.xiaoxu.test.TestAtomic
 */
public class TestAtomic {
    @AllArgsConstructor
    @ToString
    @Data
    static class User {
        String name;
        int age;
    }

    static UnaryOperator<User> un = (t) -> {
        if(t==null){
            return new User("defualt",1000);
        }
        return new User("xiaoli",17);
    };

    static BinaryOperator<User> bina = (t,newUser) ->{
      if(t==null||newUser==null){
          return new User("default",999);
      }
      return new User(t.getName()+"|"+newUser.getName(),t.getAge()+newUser.getAge());
    };

    public static void useMethods(){
        AtomicReference<User> atomic = new AtomicReference<>();
        User a = new User("xiaoxu",15);
        atomic.set(a);
        System.out.println("用户1:"+atomic);
        System.out.println("老用户1:"+atomic.getAndUpdate(un)+"\t新用户1:"+atomic.get());

        System.out.println("用户2:"+atomic.get());
        System.out.println("老用户2:"+atomic.updateAndGet((t)->new User("mary",99))+"\t新用户2:"+atomic.get());
    }

    public static void useMethods2(){
        AtomicReference<User> atomic = new AtomicReference<>();
        User a = new User("xiaoxu",15);
        atomic.set(a);
        System.out.println("用户1:"+atomic);

        System.out.println("老用户1:"+atomic.getAndAccumulate(new User("第一个",99),bina)+"\t新用户1:"+atomic.get());

        System.out.println("用户2:"+atomic.get());
        System.out.println("老用户2:"+atomic.accumulateAndGet(new User("第二个",11),bina)+"\t新用户2:"+atomic.get());
    }

    public static void main(String[] args) {
        useMethods();
        System.out.println("\n****\n");
        useMethods2();
    }

}

执行如下:

用户1:TestAtomic.User(name=xiaoxu, age=15)
老用户1:TestAtomic.User(name=xiaoxu, age=15)	新用户1:TestAtomic.User(name=xiaoli, age=17)
用户2:TestAtomic.User(name=xiaoli, age=17)
老用户2:TestAtomic.User(name=mary, age=99)	新用户2:TestAtomic.User(name=mary, age=99)

****

用户1:TestAtomic.User(name=xiaoxu, age=15)
老用户1:TestAtomic.User(name=xiaoxu, age=15)	新用户1:TestAtomic.User(name=xiaoxu|第一个, age=114)
用户2:TestAtomic.User(name=xiaoxu|第一个, age=114)
老用户2:TestAtomic.User(name=xiaoxu|第一个|第二个, age=125)	新用户2:TestAtomic.User(name=xiaoxu|第一个|第二个, age=125)

可知:

1.getAndUpdate和updateAndGet,参数为UnaryOperator< V > updateFunction,一元操作,对引用对象做替换作用;

2.getAndAccumulate和accumulateAndGet,参数为V x,BinaryOperator< V > accumulatorFunction,二元操作,对引用对象和新对象参数x做积累作用.

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值