All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.core.node.ConcurrentLSNode Maven / Gradle / Ivy

There is a newer version: 2024.0.2
Show newest version
package shz.core.node;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * 元素类型为E支持并发的单向链表节点
 * 

* [16+E(类型字节)+对齐填充]*n(n为元素个数) *

* B=16*(n+1)+(E+对齐填充)*n */ @SuppressWarnings({"restriction"}) public class ConcurrentLSNode implements SNode> { private static final long serialVersionUID = 2243716435843150664L; public volatile E val; protected volatile ConcurrentLSNode next; protected ConcurrentLSNode(E val) { this.val = val; } public static ConcurrentLSNode of(E e) { return new ConcurrentLSNode<>(e); } public static ConcurrentLSNode of() { return of(null); } private static final AtomicReferenceFieldUpdater valUpdater = AtomicReferenceFieldUpdater.newUpdater(ConcurrentLSNode.class, Object.class, "val"); private static final AtomicReferenceFieldUpdater nextUpdater = AtomicReferenceFieldUpdater.newUpdater(ConcurrentLSNode.class, ConcurrentLSNode.class, "next"); public final boolean casVal(E expect, E update) { return valUpdater.compareAndSet(this, expect, update); } public final boolean casNext(ConcurrentLSNode expect, ConcurrentLSNode update) { return nextUpdater.compareAndSet(this, expect, update); } @Override public final ConcurrentLSNode next() { return next; } @Override public final void next(ConcurrentLSNode node) { next = node; } @Override public final ConcurrentLSNode addNext(ConcurrentLSNode node) { ConcurrentLSNode next; do { next = this.next; node.next = next; } while (!casNext(next, node)); return node; } @Override public final ConcurrentLSNode addPrev(ConcurrentLSNode node) { ConcurrentLSNode clsNode = addNext(node); E val; do { val = this.val; } while (!casVal(val, clsNode.val)); clsNode.val = val; return this; } @Override public final void poll() { if (next == null) this.val = null; else { ConcurrentLSNode next = this.next; if (casNext(next, next.next)) this.val = next.val; } } public final ConcurrentLSNode addNext(E e) { return addNext(of(e)); } @SafeVarargs public final ConcurrentLSNode addNext(E... es) { ConcurrentLSNode next = this; for (E e : es) next = next.addNext(e); return next; } public final ConcurrentLSNode addPrev(E e) { return addPrev(of(e)); } @SafeVarargs public final ConcurrentLSNode addPrev(E... es) { for (E e : es) addPrev(e); return this; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy