• AtomicReference


    AtomicReference就是以原子方式更新对象引用,可以看看源码:

    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;
        }

    可以看出它是利用unsafe类提供的方法来进行的,

    使用场景,当两个线程同时去更新数据库内容,那么就会存在问题

    假设a先执行,b后执行,操作变量a就会造成问题,

    方法一,在执行sql的时候带上原来就有的值:

    update set money =#{value} where id=#{id} and money=#{oldValue}

    那么你更新时候就不会出现同时更新,

    再看另一种方法案例:

    package com.cxy.ssp.Automic;
    
    import java.util.concurrent.atomic.AtomicReference;
    
    public class Demo2 {
        private static AtomicReference<Integer> atomicReference =new AtomicReference<>(0);
    
        public static void main(String[] args) {
            atomicReference.compareAndSet(0,1);
            System.out.println(atomicReference.get());
            atomicReference.compareAndSet(1,3);
            System.out.println(atomicReference.get());
    
            atomicReference.compareAndSet(1,5);
            System.out.println(atomicReference.get());
        }
    
    
    }
  • 相关阅读:
    Alice and Bob 要用到辗转相减
    Java经典设计模式
    设计模式---创建类---建造者模式
    luogu4267 TamingtheHerd (dp)
    nowcoder172C 保护 (倍增lca+dfs序+主席树)
    nowcoder172A 中位数 (二分答案)
    bzoj4985 评分 (二分答案+dp)
    luogu4269 Snow Boots G (并查集)
    luogu4268 Directory Traversal (dfs)
    bzoj1001/luogu4001 狼抓兔子 (最小割/平面图最小割转对偶图最短路)
  • 原文地址:https://www.cnblogs.com/xiufengchen/p/11562041.html
Copyright © 2020-2023  润新知