什么时候引用需要是原子的? [英] When does a reference need to be atomic?

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

问题描述

在Java中以原子方式分配引用意味着什么?

What does it mean for a reference to be assigned atomically in Java?


  • 我明白这意味着什么是长和双,即:一个线程可以看到部分构造的数字,

  • 但对于一个我不理解的对象,因为赋值并不意味着复制只是指向内存中的地址

那么,如果引用赋值在Java中不是原子的,可能会出错?

So what could have been wrong if reference assignment was not atomic in Java?

推荐答案

这意味着你永远不会得到损坏的引用。假设您有以下类:

This means that you will not get the corrupted reference ever. Suppose that you have the following class:

class MyClass {
    Object obj = null;
}

内存 obj 是一个空指针,通常它是一个整数,如 0x00000000 。然后假设在一个线程中你有一个任务:

In memory obj is a null pointer, usually it's an integer number like 0x00000000. Then suppose that in one thread you have an assignment:

this.obj = new Object();

假设分配了 new Object()在内存中,并有像 0x12345678 这样的指针。参考原子性确保当您从另一个线程检查 obj 时,您将具有空指针( 0x00000000 )或指向新对象的指针( 0x12345678 )。但在任何情况下,您都无法获得部分分配的引用(如 0x12340000 ),这些引用无处可寻。

Suppose that new Object() is allocated in the memory and has the pointer like 0x12345678. The reference atomicity ensures that when you check the obj from another thread you will either have a null pointer (0x00000000) or pointer to the new object (0x12345678). But under no circumstances you can get the partially assigned reference (like 0x12340000) which points to nowhere.

这可能看起来很明显,但这种问题可能会出现在低级语言中,例如 C ,具体取决于CPU架构和记忆对齐。例如,如果指针未对齐并穿过缓存行,则可能无法同步更新。为了避免这种情况,Java虚拟机总是对齐指针,因此它们永远不会跨越缓存行。

This might look obvious, but such problem may appear in low-level languages like C depending on the CPU architecture and memory alignment. For example if your pointer is misaligned and crosses the cache line, it's possible that it will not be synchronously updated. In order to avoid such situation Java virtual machine always aligns pointers, so they never cross the cache line.

因此Java引用是非原子的,会有机会当解除引用从另一个线程写入的引用时,你得到的不是在赋值之前或之后引用的对象,而是随机内存位置(这可能导致分段错误,损坏的堆或任何其他灾难)。

So were the Java references non-atomic, there would be a chance when dereferencing the reference written from another thread that you get not the object which was referenced before or after the assignment, but random memory location (which may lead to segmentation fault, corrupted heap or any other disaster).

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

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