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);
    ths[i].start();
}
//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.

Cheers!!

DZone

责编内容by:DZone阅读原文】。感谢您的支持!

您可能感兴趣的

原 荐 Java数据校验详解 一切从元编程开始 一个健壮的系统都要对外部提交的数据进行完整性、合法性的校验。即使开发一个不面对最终用户的工具包,也需要对传入的数据进行缜密的校验来防止引发底层难以追踪的问题。各路大神当然也会注意到这个问题,所以在“元编程”(见 ...
Java并发编程原理与实战八:产生线程安全性问题原因(javap字节码分析)... 前面我们说到多线程带来的风险,其中一个很重要的就是安全性,因为其重要性因此,放到本章来进行讲解,那么线程安全性问题产生的原因,我们这节将从底层字节码来进行分析。 一、问题引出 先看一段代码 package com.rooco...
Pay System ——基于 Java 的开源易支付系统... Pay System 易支付 是一个聚合支付系统,支持微信/支付宝/QQ 聚合支付,包括PC端,移动端H5支付. 功能简介: 1.支持对接 微信/支付宝/QQ钱包 支付 2.支持 三通道退款接口(微信/支付宝/QQ钱包) 3...
Wait notify in java class Callme { void call(String msg) { System.out.print(""); } }class Caller implements Runnable {...
Java 空集合使用场景及填坑 今天学学Java中如何创建一个空集合以及空集合的一些使用场景和相关的坑。你可能会问,这好像没有什么好讲的,空集合不就是 new 一个嘛,也就是像 new ArrayList() 这样创建一个不久行了吗?其实这也是一种创建...