【问题标题】:Possible to create AtomicReference that can be swapped atomically?可以创建可以原子交换的 AtomicReference 吗?
【发布时间】:2011-06-15 12:09:06
【问题描述】:

有没有办法实现一种引用类型,它的值可以与另一个原子交换?


在 Java 中,AtomicReference 可以与局部变量交换,但不能与另一个 AtomicReference 交换。

你可以这样做:

AtomicReference r1 = new AtomicReference("hello");
AtomicReference r2 = new AtomicReference("world");

并通过两种操作的组合交换它们:

r1.set(r2.getAndSet(r1.get()));

但这使它们之间的状态不一致,两者都包含"hello"。此外,即使你可以原子地交换它们,你仍然不能原子地读取它们(作为一对)。


我想做的是:

PairableAtomicReference r1 = new PairableAtomicReference("hello");
PairableAtomicReference r2 = new PairableAtomicReference("world");
AtomicRefPair rp = new AtomicRefPair(r1, r2);

然后

Object[] oldVal, newVal;
do {
    oldVal = rp.get();
    newVal = new Object[] {oldVal[1], oldVal[0]};
} while (! rp.compareAndSet(oldVal, newVal));

交换值,并在另一个线程中:

AtomicRefPair otherRP = new AtomicRefPair(r1, r2);
System.out.println(Arrays.toString(otherRP.get()));

并确保输出为[hello, world][world, hello]

注意事项:

  • r1r2 已配对用于此操作,但另一个线程可能会独立配对,例如 r1 和另一个 r3(不幸的是,这意味着我不能使用 this solution。)
  • 将有数十万个这样的引用,因此全局 ReentrantLock 将是一个主要瓶颈。
  • rpotherRP 不一定在线程之间共享,因此简单地锁定它们是行不通的。它们可能是interned,但实习生池需要自己的同步,这将是另一个瓶颈。
  • 我在这里只进行了 2 组参考,但能够进行 3 组或更多组将是一个奖励。

是否可以实现AtomicRefPair 的无锁版本?我有一种预感,但如果不是,那么也许某处有一篇文章解释了原因?


相关How do I atomically swap 2 ints in C#?

【问题讨论】:

  • Guava 中有一个 Interner,它使用 ConcurrentHashMap,所以争用平均可以任意小。

标签: java interlocked atomicreference atomic-swap


【解决方案1】:

有一个不可变的类持有该对。那是你的原子。交换对意味着替换原子。

更新:您的问题不是很清楚。但一般来说,对于由多个变量组成的并发系统,可能需要

  1. 拍摄系统状态的快照。快照一旦拍摄就不会改变。
  2. 通过一次更改多个变量以原子方式更新系统状态。可能需要在我的更新和之前的快照(我的计算基于)之间没有其他更新

如果不消耗太多资源,您可以直接在快照中为系统建模。

【讨论】:

  • @finnw - 这个答案有什么问题?这是一个合理(而且复杂得多)的解决方案。
  • 我指的是r1r2 可以配对用于一个操作,r1r3 可以配对用于另一个操作。这原则上可行,但需要一种动态重新组合引用的方法。
  • @finnw - 嗯,上次我阅读了你的帖子,我错过了关于动态分组的部分。现在我明白了。
【解决方案2】:

我不知道是否有一个很好的解决方案,但以下丑陋的解决方案可以工作:

public final class MyReference<T> extends ReentrantLock implements Comparable<MyReference<T>> {
    public MyReference() {
        id = counter.incrementAndGet();
    }

    public void swap(MyReference<T> other) {
        if (id < other.id) {
            lock();
            other.lock();
        } else {
            other.lock();
            lock();
        }
        final T tmp = value;
        value = other.value;
        other.value = tmp;
        unlock();
        other.unlock();
    }

    public static <T> List<T> consistentGet(List<MyReference<T>> references) {
        final ArrayList<MyReference<T>> sortedReferences = Lists.newArrayList(references);
        Collections.sort(sortedReferences);
        for (val r : sortedReferences) r.lock();
        final List<T> result = Lists.newArrayListWithExpectedSize(sortedReferences.size());
        for (val r : references) result.add(r.value);
        for (val r : sortedReferences) r.unlock();
        return result;
    }

    @Override
    public int compareTo(MyReference<T> o) {
        return id < o.id ? -1 : id > o.id ? 1 : 0;
    }

    private final static AtomicInteger counter = new AtomicInteger();

    private T value;
    private final int id;
}
  • 使用 MyReference 代替 AtomicReference。
  • 它使用了很多锁,但没有一个是全局的。
  • 它以固定的顺序获取锁,因此没有死锁。
  • 它使用 lombok 和 guava 进行编译(将其视为没有它们的伪代码)。

【讨论】:

  • +1。几乎是我想建议的。然而,op 需要“数十万个这样的参考”。也许将它们分组到分区并将锁与这些分区相关联会更好,这与ConcurrentHashMap 的工作方式几乎相同。如果分区的数量相当大,争用的概率应该很低。
  • 我不会,因为 ReentrantLock 很小,因为它只包含一个对空对象的引用。所以即使是 100 万个也只需要 24 MB(假设每个引用 8B,每个对象 16B)。
  • @maaartinus,对 lombok 的引用在哪里?
  • for (val r : ...),其中val来自projectlombok.org/features/val.html
  • 为什么类MyReference派生ReentrantLock?您是否尝试节省在每个 MyReference 实例中存储 Lock 引用的空间?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多