com.conversantmedia.util.concurrent.PushPullConcurrentQueue Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of disruptor Show documentation
Show all versions of disruptor Show documentation
Conversant Disruptor - very high throughput Java BlockingQueue
package com.conversantmedia.util.concurrent;
/*
* #%L
* Conversant Disruptor
* ~~
* Conversantmedia.com © 2016, Conversant, Inc. Conversant® is a trademark of Conversant, Inc.
* ~~
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.concurrent.atomic.AtomicLong;
/**
* Tuned version of Martin Thompson's push pull queue
*
* Transfers from a single thread writer to a single thread reader are orders of nanoseconds (3-5)
*
* Created by jcairns on 5/28/14.
*/
public class PushPullConcurrentQueue implements ConcurrentQueue {
protected final int size;
protected final long mask;
protected final E[] buffer;
protected final AtomicLong tail = new PaddedAtomicLong(0L);
protected final AtomicLong head = new PaddedAtomicLong(0L);
protected final PaddedLong tailCache = new PaddedLong();
protected final PaddedLong headCache = new PaddedLong();
public PushPullConcurrentQueue(final int size) {
int rs = 1;
while(rs < size) rs <<= 1;
this.size = rs;
this.mask = rs-1;
buffer = (E[])new Object[this.size];
}
@Override
public boolean offer(final E e) {
if(e != null) {
final long tail = this.tail.get();
final long queueStart = tail - size;
if((headCache.value > queueStart) || ((headCache.value = head.get()) > queueStart)) {
final int dx = (int) (tail & mask);
buffer[dx] = e;
this.tail.lazySet(tail+1L);
return true;
} else {
return false;
}
} else {
throw new NullPointerException("Invalid element");
}
}
@Override
public E poll() {
final long head = this.head.get();
if((head < tailCache.value) || (head < (tailCache.value = tail.get()))) {
final int dx = (int)(head & mask);
final E e = buffer[dx];
buffer[dx] = null;
this.head.lazySet(head+1L);
return e;
} else {
return null;
}
}
@Override
public int remove(final E[] e) {
int n = 0;
headCache.value = this.head.get();
final int nMax = e.length;
for(long i = headCache.value, end = tail.get(); n