How AtomicReference Works in Java

综合编程 2018-05-16 阅读原文

AtomicReference is still not clear to some people, so I would like to say a few words about it and provide a GitHub link
with full-fledged running code.

AtomicReference refers to an object reference. This reference is a volatile member variable in the AtomicReference instance as below.

private volatile V value;

get() simply returns the latest value of the variable (as volatiles do in a "happens before" manner).

public final V get()
public final boolean  compareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);

The compareAndSet(expect,update) method calls the compareAndSwapObject() method of the unsafe class of Java. This method call of unsafe invokes the native call, which invokes a single instruction to the processor. "expect" and "update" each reference an object.

If and only if the AtomicReference instance member variable "value" refers to the same object is referred to by "expect", "update" is assigned to this instance variable now, and "true" is returned. Or else, false is returned. The whole thing is done atomically. No other thread can intercept in between.

The main advantage is that we do not need to use the resource consuming synchronized keyword. As we call synchronized, the following happens.

  1. The cache and registers are flushed for the running thread, which will eventually have the monitor.

  2. We create a memory barrier, and only this thread has the monitor of the object we are synchronizing.

  3. After the synchronized block ends, the variables are written into memory.

But in the case of compareAndSet(...,...) all of the above do not happen.

I have created a very small example of a ticket booking program and posted it to GitHub. The single file application can be downloaded and run in Eclipse. It is self-explanatory, and here, I provide the snippet that will clarify what the program is trying to do.

for (int i = 0; i < 4; i++) {// 4 seats, user threads will try to reserve seats
    seats.add(new AtomicReference());
Thread[] ths = new Thread[8];// 8 users, each is a thread
for (int i = 0; i < ths.length; i++) {
    ths[i] = new MyTh(seats, i);
//as the number of users is greater, everyone cannot reserve a seat.

Here is the GitHub link again
. Just download the single source code file, add it to some Java project in Eclipse, resolve any errors due to import- or package-related issues, and run it.





java多线程那点事儿 前段时间应隔壁部门大佬的邀约,简单地帮他们部门的童靴梳理了下多线程相关的内容,客串了一把讲师【因为部门内有不少是c#转java的童鞋,所以讲的稍微浅显了些】 ok,按照个人习惯先来大纲 知识点: 1)进程 多线程的相关概念 涉及...
Java 网络爬虫 Preface 很早之前写过一个 Java 的爬虫程序,可以爬取笔趣阁上的小说。最近突然有爬点书看看的想法,遂翻到原先的代码,简直不忍直视。好在现在编码能力有所提升,而且团队内一直强调重构的重要性,所以重新拾起这个爬虫程序,好好重构一...
Threading with Style Thread-first -> is ideal for navigating large, nested structures. The shape even suggests direction . The func...
Differentiate if this is a redirect: or ... How do I differentiate between a redirect: or not in HandlerInterceptorAdaptor.preHandle()? I need to clear a session at...
Java 模板引擎 Beetl 2.7.28 发布,Bug 修复和新增功能... 新增 #344 新增hasAttribute判断对象是否有属性 修复 #343 Tomcat 热部署的内存泄露警告信息移除 Maven com.ibeetl beetl 2.7.28 ...