可以创建可以原子交换的AtomicReference吗?
有没有办法实现一种类型的引用,其值可以与另一个原子交换?
在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
(不幸的是,这意味着我不能使用这个解决方案。)
将有数十万个这样的参考文献,因此全球ReentrantLock
将成为主要瓶颈。
rp
和otherRP
不一定在线程之间共享,因此简单地锁定它们将不起作用。他们可以被实习,但实习池需要自己的同步,这将是另一个瓶颈。
我这里只制作了2个参考组,但是组合3个或更多的能力将是一个奖励。
是否可以实现AtomicRefPair
的无锁版本?我有预感它不是,但如果没有,那么也许有一篇文章可以解释为什么?
相关:如何在C#中自动交换2个int?
没有找到相关结果
已邀请:
2 个回复
车料
使用MyReference而不是AtomicReference。 它使用了很多锁,但它们都不是全局的。 它以固定的顺序获取锁,因此它没有死锁。 它使用lombok和guava进行编译(将其作为伪代码而不使用它们)。
捐焦