shz.core.node.ConcurrentLDNode Maven / Gradle / Ivy
package shz.core.node;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* 元素类型为E支持并发的双向链表节点
*
* [24+E(类型字节)+对齐填充]*n(n为元素个数)
*
* B=16+24*n+(E+对齐填充)*n
*/
@SuppressWarnings({"restriction"})
public class ConcurrentLDNode implements DNode> {
private static final long serialVersionUID = 800394184406446745L;
public volatile E val;
protected volatile ConcurrentLDNode next;
protected volatile ConcurrentLDNode prev;
protected ConcurrentLDNode(E val) {
this.val = val;
}
public static ConcurrentLDNode of(E e) {
return new ConcurrentLDNode<>(e);
}
public static ConcurrentLDNode of() {
return of(null);
}
private static final AtomicReferenceFieldUpdater valUpdater = AtomicReferenceFieldUpdater.newUpdater(ConcurrentLDNode.class, Object.class, "val");
private static final AtomicReferenceFieldUpdater nextUpdater = AtomicReferenceFieldUpdater.newUpdater(ConcurrentLDNode.class, ConcurrentLDNode.class, "next");
private static final AtomicReferenceFieldUpdater prevUpdater = AtomicReferenceFieldUpdater.newUpdater(ConcurrentLDNode.class, ConcurrentLDNode.class, "prev");
public boolean casVal(E expect, E update) {
return valUpdater.compareAndSet(this, expect, update);
}
public boolean casNext(ConcurrentLDNode expect, ConcurrentLDNode update) {
return nextUpdater.compareAndSet(this, expect, update);
}
public boolean casPrev(ConcurrentLDNode expect, ConcurrentLDNode update) {
return prevUpdater.compareAndSet(this, expect, update);
}
@Override
public final ConcurrentLDNode next() {
return next;
}
@Override
public final void next(ConcurrentLDNode node) {
next = node;
}
@Override
public final ConcurrentLDNode prev() {
return prev;
}
@Override
public final void prev(ConcurrentLDNode node) {
prev = node;
}
@Override
public final ConcurrentLDNode addNext(ConcurrentLDNode node) {
while (true) {
ConcurrentLDNode next = this.next;
node.prev = this;
node.next = next;
if (!casNext(next, node)) continue;
if (next != null) next.prev = node;
break;
}
return node;
}
@Override
public final ConcurrentLDNode addPrev(ConcurrentLDNode node) {
while (true) {
ConcurrentLDNode prev = this.prev;
node.prev = prev;
node.next = this;
if (!casPrev(prev, node)) continue;
if (prev != null) prev.next = node;
break;
}
return node;
}
@Override
public final void poll() {
ConcurrentLDNode prev = this.prev;
ConcurrentLDNode next = this.next;
if (prev != null) {
if (prev.casNext(this, next)) if (next != null) next.prev = prev;
} else if (next != null) next.casPrev(this, null);
}
public final ConcurrentLDNode addNext(E e) {
return addNext(of(e));
}
@SafeVarargs
public final ConcurrentLDNode addNext(E... es) {
ConcurrentLDNode next = this;
for (E e : es) next = next.addNext(e);
return next;
}
public final ConcurrentLDNode addPrev(E e) {
return addPrev(of(e));
}
@SafeVarargs
public final ConcurrentLDNode addPrev(E... es) {
ConcurrentLDNode prev = this;
for (E e : es) prev = prev.addPrev(e);
return prev;
}
}