为什么Java中的引用分配是原子的? [英] Why is reference assignment atomic in Java?

查看:90
本文介绍了为什么Java中的引用分配是原子的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在64位JVM中,引用分配是原子的. 现在,我假设jvm在内部不使用原子指针对此建模,因为否则将不需要原子引用.所以我的问题是:

As far as I know reference assignment is atomic in a 64 bit JVM. Now, I assume the jvm doesn't use atomic pointers internally to model this, since otherwise there would be no need for Atomic References. So my questions are:

原子引用分配是否在java/Scala的规范"中并保证会发生?或者大多数情况下是这种巧合吗?

Is atomic reference assignment in the "specs" of java/Scala and guaranteed to happen or is it just a happy coincidence that it is that way most times ?

原子引用分配是否暗示任何可编译为JVM字节码的语言(例如clojure,Groovy,JRuby,JPython等)?

Is atomic reference assignment implied for any language that compiles to the JVM's bytecode (e.g. clojure, Groovy, JRuby, JPython...etc) ?

如何在内部不使用原子指针的情况下将引用赋值为原子?

How can reference assignment be atomic without using an atomic pointer internally ?

推荐答案

首先,引用分配是原子的,因为规范中是这样说的.除此之外,对于JVM实现者来说,实现这一约束没有任何障碍,因为64位引用通常仅用于64位体系结构,而原子64位分配是免费的.

First of all, reference assignment is atomic because the specification says so. Besides that, there is no obstacle for JVM implementors to fulfill this constraint, as 64 Bit references are usually only used on 64 Bit architectures, where atomic 64 Bit assignment comes for free.

您的主要困惑是基于这样的假设,即由于其名称,附加的原子引用"功能正好意味着这一点.但是AtomicReference类提供了更多的功能,因为它封装了volatile引用,该引用在多线程执行中具有更强的内存可见性保证.

Your main confusion stems from the assumption that the additional "Atomic References" feature means exactly that, due to its name. But the AtomicReference class offers far more, as it encapsulates a volatile reference, which has stronger memory visibility guarantees in a multi-threaded execution.

进行原子引用更新并不一定意味着读取引用的线程还将看到与通过该引用可到达的对象的 fields 有关的一致值.它所保证的是,您将读取null引用或对某个线程实际存储的现有对象的有效引用.如果需要更多保证,则需要同步,volatile引用或AtomicReference之类的构造.

Having an atomic reference update does not necessarily imply that a thread reading the reference will also see consistent values regarding the fields of the object reachable through that reference. All it guarantees is that you will read either the null reference or a valid reference to an existing object that actually was stored by some thread. If you want more guarantees, you need constructs like synchronization, volatile references, or an AtomicReference.

AtomicReference还提供 atomic update 操作,例如compareAndSetgetAndSet.使用普通参考变量是不可能的.

AtomicReference also offers atomic update operations like compareAndSet or getAndSet. These are not possible with ordinary reference variables.

这篇关于为什么Java中的引用分配是原子的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆