java 中 AtomicMarkableReference 的 "get" 方法实现背后的原因是什么?

What is the reason behind "get" method implementation of AtomicMarkableReference in java?

在 java 中,AtomicMarkableReference 可用于自动更新对象引用以及标记位。

javadoc 状态:

Implementation note: This implementation maintains markable references by creating internal objects representing "boxed" [reference, boolean] pairs.

根据 class 的 java8 源代码可以看出,这是真的:

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
}

class的get方法的设计背后有什么原因吗?

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

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

这是因为 Java 没有 Pair<L, R> class 并且可能不会,尽管标准库至少有三个 class private static class Pair。添加 Pair class 已被 OpenJDK 开发人员不止一次讨论过,但始终被拒绝。 This 邮件很好地解释了为什么不应将配对作为标准呈现 class(另外,整个邮件线程非常有用):

The problem is that classes like Pair simply go that much further to indulge the desire to never have to create any actual types of our own. When we're forced to create our own types, we begin to model our data more appropriately, which I believe leads us to create good abstractions at broader levels of granularity as well.

只要 AtomicMarkableReference 不公开它的 Pair class 并且在 Java 中你就不能改变传递引用的值(以这样的方式change will be observed by caller), return 引用和位标志的唯一方法是 return 其中之一来自方法并将第二个设置为作为参数数组传递。所以这与并发无关,也与遗留无关,而是与语言设计决策有关。