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

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

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

import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

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

* 16*n(n为元素个数) *

* B=16*(n+1) */ @SuppressWarnings("restriction") public class ConcurrentJSNode implements SNode { private static final long serialVersionUID = -6374622330255464371L; public volatile long val; protected volatile ConcurrentJSNode next; protected ConcurrentJSNode(long val) { this.val = val; } public static ConcurrentJSNode of(long e) { return new ConcurrentJSNode(e); } public static ConcurrentJSNode of() { return of(0L); } private static final AtomicLongFieldUpdater valUpdater = AtomicLongFieldUpdater.newUpdater(ConcurrentJSNode.class, "val"); private static final AtomicReferenceFieldUpdater nextUpdater = AtomicReferenceFieldUpdater.newUpdater(ConcurrentJSNode.class, ConcurrentJSNode.class, "next"); public final boolean casVal(long expect, long update) { return valUpdater.compareAndSet(this, expect, update); } public final boolean casNext(ConcurrentJSNode expect, ConcurrentJSNode update) { return nextUpdater.compareAndSet(this, expect, update); } @Override public final ConcurrentJSNode next() { return next; } @Override public final void next(ConcurrentJSNode node) { next = node; } @Override public final ConcurrentJSNode addNext(ConcurrentJSNode node) { ConcurrentJSNode next; do { next = this.next; node.next = next; } while (!casNext(next, node)); return node; } @Override public final ConcurrentJSNode addPrev(ConcurrentJSNode node) { ConcurrentJSNode cjsNode = addNext(node); long val; do { val = this.val; } while (!casVal(val, cjsNode.val)); cjsNode.val = val; return this; } @Override public final void poll() { if (next == null) this.val = 0L; else { ConcurrentJSNode next = this.next; if (casNext(next, next.next)) this.val = next.val; } } public final ConcurrentJSNode addNext(long e) { return addNext(of(e)); } public final ConcurrentJSNode addNext(long... es) { ConcurrentJSNode next = this; for (long e : es) next = next.addNext(e); return next; } public final ConcurrentJSNode addPrev(long e) { return addPrev(of(e)); } public final ConcurrentJSNode addPrev(long... es) { for (long e : es) addPrev(e); return this; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy