AtomicInteger实现机制

来源:互联网 发布:清单打印软件免费版 编辑:程序博客网 时间:2024/06/05 19:26

1  AtomicInteger应用场景。

首先来看下sun官方对AtomicInteger的定义.

/** * An {@code int} value that may be updated atomically.  See the * {@link java.util.concurrent.atomic} package specification for * description of the properties of atomic variables. An * {@code AtomicInteger} is used in applications such as atomically * incremented counters, and cannot be used as a replacement for an * {@link java.lang.Integer}. However, this class does extend * {@code Number} to allow uniform access by tools and utilities that * deal with numerically-based classes. * * @since 1.5 * @author Doug Lea*/

大概意思是,AtomiocInteger的作用是在并发的情况下计数这么一个作用。
那它是怎样实现的呢?如果说没有看过源码。我首先蹦出的一个想法是:这必须是对访问量进行加锁嘛。事实是这样子吗?接下来来看看源码的实现。

 // setup to use Unsafe.compareAndSwapInt for updates<span style="font-size:18px;">    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;</span>

在它里面封装了一个value 。用关键字volatile来修饰。
那这个volatile什么作用呢?
在多线程中,为了快速的访问变量的值,线程本身会有内存中相关变量的缓存。线程修改这个值后,其他线程并不能立即得到这个修改后的结果。
但是用volatile这个关键字来修饰的话,线程本身并不会缓存这个变量,而是把这个修改过的值直接刷新到内存中。这样这个修改后的值对于其他线程来说就变得可见。

但是有一点要特别警惕:用volatile并不能保证原子操作。所以说你要统计一个网站的访问量,你光用volatile肯定是行不通的。 那这个AtomiocInteger是如何实现统计技术的呢?
我们注意到它用到了一个平时我们不怎么用到的类:Unsafe.这个类是干嘛的呢?
这个类是用于执行低级别、不安全操作的方法集合。通常情况下,只有jdk的代码才能使用这个类。

查看源码我们知道对于值得修改,都会用到valueOffset这么一个偏移量。这是属性值在内存中的偏移量。(学过c++的人可能更好理解一点)。接下来简单的分析一下 getAndIncrement 这个方法。
public final int getAndIncrement() {        for (;;) {            int current = get();            int next = current + 1;            if (compareAndSet(current, next))                return current;        }    }

 这个方法的作用很简单,就是在当前的变量值基础上加1。

然后我们再来看看compareAndSet这个方法。

public final boolean compareAndSet(int expect, int update) {        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);    }

  在这里我们看到了这个偏移量的作用。通过偏移量我们计算出内存地址。通过读取当前内存地址的值与expect的值是否相同,如果相同,则把update写入计算出来的内存地址,返回true.如果与expect的值不相同,说明这个变量已经被其他线程所修改,则返回false。(由于volatile关键字修饰保证我们不会读到脏数据

当没有更新成功的时候,for(;;)语句会不断的去尝试。直到成功为止。
这样一个分析就成功了。
你会发现这种机制比加锁效率更高。
1 0
原创粉丝点击