【发布时间】: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]。
注意事项:
-
r1和r2已配对用于此操作,但另一个线程可能会独立配对,例如r1和另一个r3(不幸的是,这意味着我不能使用 this solution。) - 将有数十万个这样的引用,因此全局
ReentrantLock将是一个主要瓶颈。 -
rp和otherRP不一定在线程之间共享,因此简单地锁定它们是行不通的。它们可能是interned,但实习生池需要自己的同步,这将是另一个瓶颈。 - 我在这里只进行了 2 组参考,但能够进行 3 组或更多组将是一个奖励。
是否可以实现AtomicRefPair 的无锁版本?我有一种预感,但如果不是,那么也许某处有一篇文章解释了原因?
【问题讨论】:
-
Guava 中有一个 Interner,它使用 ConcurrentHashMap,所以争用平均可以任意小。
标签: java interlocked atomicreference atomic-swap