java.util.concurrent.atomic原子操作类

java原子操作类

1.原子操作类

java.util.concurrent.atomic 的包里有AtomicBoolean, AtomicInteger,AtomicLong,AtomicLongArray,
AtomicReference等原子类的类,主要用于在高并发环境下的高效程序处理,来帮助我们简化同步处理.

在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。

2.AtomicInteger的基本方法

2.1 创建一个不传值的,默认值为0

   @Test
    public void testAtomic1(){
        AtomicInteger i = new AtomicInteger();
        System.out.println(i.get());
    }

2.2 获取和赋值

 @Test
    public void testAtomic2(){
        AtomicInteger i = new AtomicInteger();
        System.out.println(i.get());
        i.set(999); //设置当前值
        System.out.println(i.get());
    }

2.3 compareAndSet方法

    @Test
    public void testAtomic3(){
        AtomicInteger i = new AtomicInteger();
        System.out.println(i.get());
        int expect =123;
        int newint =234;
        boolean b = i.compareAndSet(expect, newint);
        System.out.println(b);
        System.out.println(i);
    }

输出结果为: 0 false 0

@Test
    public void testAtomic4(){
        AtomicInteger atomicInteger = new AtomicInteger(123);
        System.out.println(atomicInteger.get());

        int expectedValue = 123;
        int newValue      = 234;
        Boolean b =atomicInteger.compareAndSet(expectedValue, newValue);
        System.out.println(b);
        System.out.println(atomicInteger);
    }

输出结果为: 123 true 234

由上可知该方法表示,atomicInteger的值与expectedValue相比较,如果不相等,则返回false,
atomicInteger原有值保持不变;如果两者相等,则返回true,atomicInteger的值更新为newValue

2.4 getAndAdd、AddAndGet、getAndDecrement和DecrementAndGet

public void testAtomic5(){
        AtomicInteger atomicInteger = new AtomicInteger(123);
//         获取当前值,并加10
        System.out.println(atomicInteger.getAndAdd(10));
        System.out.println(atomicInteger.get());
//       获取加10后的值
        System.out.println(atomicInteger.addAndGet(10));
        System.out.println(atomicInteger.get());

        //getAndDecrement()和decrementAndGet()方法同理
    }

3.多线程测试

package com.wk;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class Counter {
    public static AtomicInteger count = new AtomicInteger(0);
    public static void inc() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count.getAndIncrement();//count值自加1
    }

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(100);

        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Counter.inc();
                    latch.countDown();
                }
            }).start();
        }
        latch.await();

        System.out.println("运行结果:" + Counter.count);

    }
}

使用AtomicInteger,即使不用同步块synchronized,最后的结果也是100,可用看出AtomicInteger的作用,用原子方式更新的int值。如果使用普通的int类型的话,输出结果就不一定是100了。使用atomic类,可以在高并发环境下的高效程序处理,避免了synchronized锁操作。

4.AtomicReference详解

Atomic家族主要是保证多线程环境下的原子性,相比synchronized而言更加轻量级。比较常用的是AtomicInteger,作用是对Integer类型操作的封装,前文已经做了介绍,而AtomicReference作用是对普通对象的封装。

资源类

package com.wk.atomictest;

public class Student {
 
    private String name;
 
    private Integer age;
 
    public Student() {
    }
 
    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
}

AtomicReference多线程操作对象测试

package com.wk.atomictest;

import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceTest {
    public final static AtomicReference<Student> atomicStudent = new AtomicReference<>();

    public static void main(String[] args) {

        final Student student1 = new Student("乔丹", 1);
        final Student student2 = new Student("詹姆斯", 2);

        //初始值为student1对象
        atomicStudent.set(student1);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    //每个线程随机停顿 多执行几次能看出效果
                    Thread.sleep((long) Math.abs(Math.random() * 100));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //预期值 student1和 当前值(上面的atomicStudent.set(student1);)相等时候 赋予student2新的值
                if (atomicStudent.compareAndSet(student1, student2)) {
                    System.out.println(Thread.currentThread().getId() + "Change value");
                    System.out.println(atomicStudent.get().getName() + ":" + atomicStudent.get().getAge());
                } else {
                    System.out.println(Thread.currentThread().getId() + "Failed");
                }
            }).start();
        }
    }
}

5.CAS可能存在ABA的问题

CAS操作可能存在ABA的问题,就是说:假如一个值原来是A,变成了B,又变成了A,那么CAS检查时会发现它的值没有发生变化,但是实际上却变化了。一般来讲这并不是什么问题,比如数值运算,线程其实根本不关心变量中途如何变化,只要最终的状态和预期值一样即可。但是,有些操作会依赖于对象的变化过程,此时的解决思路一般就是使用版本号。在变量前面追加上版本号,每次变量更新的时候把版本号加一,那么A-B-A 就会变成(1)A - (2)B - (3)A。

5.1 AtomicStampedReference原理

AtomicStampedReference就是上面所说的加了版本号的AtomicReference。

    private static class Pair<T> {
        final T reference;
        final int stamp;
        private Pair(T reference, int stamp) {
            this.reference = reference;
            this.stamp = stamp;
        }
        static <T> Pair<T> of(T reference, int stamp) {
            return new Pair<T>(reference, stamp);
        }
    }

    private volatile Pair<V> pair;

    /**
     * Creates a new {@code AtomicStampedReference} with the given
     * initial values.
     *
     * @param initialRef the initial reference
     * @param initialStamp the initial stamp
     */
    public AtomicStampedReference(V initialRef, int initialStamp) {
        pair = Pair.of(initialRef, initialStamp);
    }

可以看到,除了传入一个初始的引用变量initialRef外,还有一个initialStamp变量,initialStamp其实就是版本号,打了一个 戳记,用来唯一标识引用变量。

在构造器内部,实例化了一个Pair对象,Pair对象记录了对象引用和版本号信息,采用int作为版本号,实际使用的时候,要保证版本号唯一(一般做成自增的)。如果版本号重复,还会出现ABA的问题。

AtomicStampedReference的所有方法,其实就是Unsafe类针对这个Pair对象的操作。和AtomicReference相比,AtomicStampedReference中的每个引用变量都带上了pair.stamp这个版本号,这样就可以解决CAS中的ABA问题了。

package com.wk.atomictest;

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceTest {

    public static void main(String[] args) {
        AtomicStampedReference<Student> atomicStampedReference = new AtomicStampedReference(null, 0);

        int[] stampHolder = new int[1];
        // 调用get方法获取引用对象和对应的版本号
        Student oldRef = atomicStampedReference.get(stampHolder);
        // stampHolder[0]保存版本号
        int oldStamp = stampHolder[0];
        boolean b = atomicStampedReference.compareAndSet(oldRef, null, oldStamp, oldStamp + 1);
        System.out.println(b);
    }
}

5.2 AtomicMarkableReference原理

我们在讲ABA问题的时候,引入了AtomicStampedReference。

AtomicStampedReference可以给引用加上版本号,追踪引用的整个变化过程,如:
A -> B -> C -> D - > A,通过AtomicStampedReference,我们可以知道,引用变量中途被更改了3次。

但是,有时候,我们并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了AtomicMarkableReference:

    private static class Pair<T> {
        final T reference;
        final boolean mark;
        private Pair(T reference, boolean mark) {
            this.reference = reference;
            this.mark = mark;
        }
        static <T> Pair<T> of(T reference, boolean mark) {
            return new Pair<T>(reference, mark);
        }
    }

    private volatile Pair<V> pair;

    /**
     * Creates a new {@code AtomicMarkableReference} with the given
     * initial values.
     *
     * @param initialRef the initial reference
     * @param initialMark the initial mark
     */
    public AtomicMarkableReference(V initialRef, boolean initialMark) {
        pair = Pair.of(initialRef, initialMark);
    }

AtomicMarkableReference和AtomicStampedReference可以给引用加上版本号唯一区别就是不再用int标识引用,而是使用boolean变量——表示引用变量是否被更改过。AtomicMarkableReference☞关注引用的变量是否被更改过。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值