private static class Node<E> { volatile E item; volatile Node<E> next; /** * Constructs a new node. Uses relaxed write because item can * only be seen after publication via casNext. */ Node(E item) { UNSAFE.putObject(this, itemOffset, item); }
它来自java.util.concurrent.ConcurrentLinkedQueue.java
什么意思,轻松写?
private static class Node<E> { volatile E item; volatile Node<E> next; /** * Constructs a new node. Uses relaxed write because item can * only be seen after publication via casNext. */ Node(E item) { UNSAFE.putObject(this, itemOffset, item); }
It comes from java.util.concurrent.ConcurrentLinkedQueue.java
What does it mean, relaxed write?
最满意答案
这是一个很好的问题。 但理解这个术语的线索在于...... JDK 9,其中sun.misc.Unsafe已成为(或将成为 - 更适合说,见此处 )公共API。
在JDK 9中,您引用的相应位置实现如下:
static final class Node<E> { volatile E item; volatile Node<E> next; /** * Constructs a node holding item. Uses relaxed write because * item can only be seen after piggy-backing publication via CAS. */ Node(E item) { ITEM.set(this, item); } ... }其中ITEM是VarHandle类的实例,它实现与sun.misc.Unsafe类似的功能。 现在,我们可以查看此方法的JavaDoc描述并找到以下内容:
将变量的值设置为newValue,设置的内存语义就像变量被声明为非易失性和非最终变量一样。 通常称为普通写访问。
换句话说,我们可以得出结论, 宽松写入与普通写入访问相同。 换句话说,我相信迈克尔上面的评论是正确的:
...它就像volatile的对立面 - 一个不能保证在线程中看到的写入。
(参见相反的方法setVolatile ,就好像变量被声明为volatile )。
It is a good question. But the clue to understanding this term lies in ... JDK 9, where sun.misc.Unsafe has become (or will become - what is more appropriate to say, see here) public API.
In JDK 9 the corresponding place, which you refers to, is implemented as follows:
static final class Node<E> { volatile E item; volatile Node<E> next; /** * Constructs a node holding item. Uses relaxed write because * item can only be seen after piggy-backing publication via CAS. */ Node(E item) { ITEM.set(this, item); } ... }Where ITEM is instance of VarHandle class which implements similar functionality as sun.misc.Unsafe. Now, we can look at this method's JavaDoc description and find the following:
Sets the value of a variable to the newValue, with memory semantics of setting as if the variable was declared non-volatile and non-final. Commonly referred to as plain write access.
In other words, we can conclude, that relaxed write is the same as plain write access. In other words, I believe that Michael's commentary above is right:
... its like the opposite of volatile - a write that is not guaranteed to be seen across threads.
(see the opposite method setVolatile which works as if the variable was declared volatile).
更多推荐
发布评论