背后的原因是什么

背后的原因是什么

本文介绍了“获取”背后的原因是什么? java中AtomicMarkableReference的方法实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,可以使用 AtomicMarkableReference 以原子方式更新对象引用以及标记位。

In java an AtomicMarkableReference can be used to update atomically an object reference along with a mark bit.

声明:

根据该类的java 8源代码中可以看到的情况,这是真的:

This is true according to what can be seen in the java 8 source code of the class:

package java.util.concurrent.atomic;

public class AtomicMarkableReference<V> {

    private static class Pair<T> {
        final T reference;
        final boolean mark;
        private Pair(T reference, boolean mark) {
            this.reference = reference;
            this.mark = mark;
        }
        static <T> Pair<T> of(T reference, boolean mark) {
            return new Pair<T>(reference, mark);
        }
    }

    private volatile Pair<V> pair;

    public AtomicMarkableReference(V initialRef, boolean initialMark) {
        pair = Pair.of(initialRef, initialMark);
    }

    // [...] class methods
}

是否有理由设计类的方法?

Is there a reason behind the design of the get method of the class?

public V get(boolean[] markHolder) {
    Pair<V> pair = this.pair;
    markHolder[0] = pair.mark;
    return pair.reference;
}

使用这样的布尔数组有什么意义(而不是返回一对值)?是并发驱动的选择吗?或者遗留代码?

What is the point of using such boolean array (instead of returning the pair of values)? Is a concurrency-driven choice? Or perhaps legacy code?

推荐答案

这是因为Java没有 Pair< L,R> 类,可能不会,即使标准库至少有三个类具有私有静态类对。 OpenJDK开发人员多次讨论添加 Pair 类,并且提案始终被拒绝。 邮件是一个非常好的解释为什么对不应该作为标准类呈现(同样,整个邮件线程非常有用):

This is because Java has no Pair<L, R> class and probably will not, even despite of the fact that standard library has at least three classes which have private static class Pair. Adding Pair class were discussed by OpenJDK developers more than once and proposal was always rejected. This mail is a very good explanation why pair shouldn't be presented as standard class (also, the whole mail thread is very useful):

只要 AtomicMarkableReference 不公开其类和Java中你不能改变传递引用的值(通过调用者可以观察到这种改变的方式),返回引用和位标志的唯一方法是返回一个它们从方法和第二个设置为作为参数数组传递。所以这不是关于并发性,也不是关于遗产,而是关于语言设计的决定。

As long as AtomicMarkableReference doesn't expose its Pair class and in Java you can't change value of passed reference (in the way that such change will be observable by caller), the only way to return both reference and bit flag is to return one of them from method and set second into passed as argument array. So it's not about concurrency, neither about legacy, it's about language design decision.

这篇关于“获取”背后的原因是什么? java中AtomicMarkableReference的方法实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:18