java.util.concurrent.atomic.AtomicLongArray Java Examples

The following examples show how to use java.util.concurrent.atomic.AtomicLongArray. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ThreadSafeBitSet.java    From hollow with Apache License 2.0 6 votes vote down vote up
/**
 * Get the segment at <code>segmentIndex</code>.  If this segment does not yet exist, create it.
 *
 * @param segmentIndex the segment index
 * @return the segment
 */
private AtomicLongArray getSegment(int segmentIndex) {
    ThreadSafeBitSetSegments visibleSegments = segments.get();

    while(visibleSegments.numSegments() <= segmentIndex) {
        /// Thread safety:  newVisibleSegments contains all of the segments from the currently visible segments, plus extra.
        /// all of the segments in the currently visible segments are canonical and will not change.
        ThreadSafeBitSetSegments newVisibleSegments = new ThreadSafeBitSetSegments(visibleSegments, segmentIndex + 1, numLongsPerSegment);

        /// because we are using a compareAndSet, if this thread "wins the race" and successfully sets this variable, then the segments
        /// which are newly defined in newVisibleSegments become canonical.
        if(segments.compareAndSet(visibleSegments, newVisibleSegments)) {
            visibleSegments = newVisibleSegments;
        } else {
            /// If we "lose the race" and are growing the ThreadSafeBitSet segments larger,
            /// then we will gather the new canonical sets from the update which we missed on the next iteration of this loop.
            /// Newly defined segments in newVisibleSegments will be discarded, they do not get to become canonical.
            visibleSegments = segments.get();
        }
    }

    return visibleSegments.getSegment(segmentIndex);
}
 
Example #2
Source File: FastBlobTypeDeserializationState.java    From zeno with Apache License 2.0 6 votes vote down vote up
/**
 * Fill this state from the serialized data which exists in this ByteArrayOrdinalMap
 *
 * @param ordinalMap
 */
public void populateFromByteOrdinalMap(final ByteArrayOrdinalMap ordinalMap) {
    ByteDataBuffer byteData = ordinalMap.getByteData();
    AtomicLongArray pointersAndOrdinals = ordinalMap.getPointersAndOrdinals();
    FastBlobDeserializationRecord rec = new FastBlobDeserializationRecord(getSchema(), byteData.getUnderlyingArray());
    for (int i = 0; i < pointersAndOrdinals.length(); i++) {
        long pointerAndOrdinal = pointersAndOrdinals.get(i);
        if(!ByteArrayOrdinalMap.isPointerAndOrdinalEmpty(pointerAndOrdinal)) {
            long pointer = ByteArrayOrdinalMap.getPointer(pointerAndOrdinal);
            int ordinal = ByteArrayOrdinalMap.getOrdinal(pointerAndOrdinal);

            int sizeOfData = VarInt.readVInt(byteData.getUnderlyingArray(), pointer);
            pointer += VarInt.sizeOfVInt(sizeOfData);

            rec.position(pointer);

            add(ordinal, rec);
        }
    }
}
 
Example #3
Source File: AtomicLongArray9Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * get and set for out of bound indices throw IndexOutOfBoundsException
 */
public void testIndexing() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int index : new int[] { -1, SIZE }) {
        final int j = index;
        final Runnable[] tasks = {
            () -> aa.getPlain(j),
            () -> aa.getOpaque(j),
            () -> aa.getAcquire(j),
            () -> aa.setPlain(j, 1),
            () -> aa.setOpaque(j, 1),
            () -> aa.setRelease(j, 1),
            () -> aa.compareAndExchange(j, 1, 2),
            () -> aa.compareAndExchangeAcquire(j, 1, 2),
            () -> aa.compareAndExchangeRelease(j, 1, 2),
            () -> aa.weakCompareAndSetPlain(j, 1, 2),
            () -> aa.weakCompareAndSetVolatile(j, 1, 2),
            () -> aa.weakCompareAndSetAcquire(j, 1, 2),
            () -> aa.weakCompareAndSetRelease(j, 1, 2),
        };

        assertThrows(IndexOutOfBoundsException.class, tasks);
    }
}
 
Example #4
Source File: MpmcAtomicArrayQueue.java    From JCTools with Apache License 2.0 6 votes vote down vote up
@Override
public E relaxedPoll() {
    final AtomicLongArray sBuffer = sequenceBuffer;
    final int mask = this.mask;
    long cIndex;
    int seqOffset;
    long seq;
    long expectedSeq;
    do {
        cIndex = lvConsumerIndex();
        seqOffset = calcCircularLongElementOffset(cIndex, mask);
        seq = lvLongElement(sBuffer, seqOffset);
        expectedSeq = cIndex + 1;
        if (seq < expectedSeq) {
            return null;
        }
    } while (// another consumer beat us to it
    seq > expectedSeq || // failed the CAS
    !casConsumerIndex(cIndex, cIndex + 1));
    final int offset = calcCircularRefElementOffset(cIndex, mask);
    final E e = lpRefElement(buffer, offset);
    spRefElement(buffer, offset, null);
    soLongElement(sBuffer, seqOffset, cIndex + mask + 1);
    return e;
}
 
Example #5
Source File: ParallelSource.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void request(long n) {
	if (Operators.validate(n)) {
		AtomicLongArray ra = parent.requests;
		for (;;) {
			long r = ra.get(index);
			if (r == Long.MAX_VALUE) {
				return;
			}
			long u = Operators.addCap(r, n);
			if (ra.compareAndSet(index, r, u)) {
				break;
			}
		}
		if (parent.subscriberCount == length) {
			parent.drain();
		}
	}
}
 
Example #6
Source File: AtomicLongArrayTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * compareAndSet in one thread enables another waiting for value
 * to succeed
 */
public void testCompareAndSetInMultipleThreads() throws InterruptedException {
    final AtomicLongArray a = new AtomicLongArray(1);
    a.set(0, 1);
    Thread t = new Thread(new CheckedRunnable() {
        public void realRun() {
            while (!a.compareAndSet(0, 2, 3))
                Thread.yield();
        }});

    t.start();
    assertTrue(a.compareAndSet(0, 1, 2));
    t.join(LONG_DELAY_MS);
    assertFalse(t.isAlive());
    assertEquals(3, a.get(0));
}
 
Example #7
Source File: Atomic8Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * All Atomic getAndUpdate methods throw NullPointerException on
 * null function argument
 */
public void testGetAndUpdateNPE() {
    Runnable[] throwingActions = {
        () -> new AtomicLong().getAndUpdate(null),
        () -> new AtomicInteger().getAndUpdate(null),
        () -> new AtomicReference().getAndUpdate(null),
        () -> new AtomicLongArray(1).getAndUpdate(0, null),
        () -> new AtomicIntegerArray(1).getAndUpdate(0, null),
        () -> new AtomicReferenceArray(1).getAndUpdate(0, null),
        () -> aLongFieldUpdater().getAndUpdate(this, null),
        () -> anIntFieldUpdater().getAndUpdate(this, null),
        () -> anIntegerFieldUpdater().getAndUpdate(this, null),
        ////() -> aLongFieldUpdater().getAndUpdate(null, Atomic8Test::addLong17),
        ////() -> anIntFieldUpdater().getAndUpdate(null, Atomic8Test::addInt17),
        ////() -> anIntegerFieldUpdater().getAndUpdate(null, Atomic8Test::addInteger17),
    };
    assertThrows(NullPointerException.class, throwingActions);
}
 
Example #8
Source File: SystemResourcesCounter.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public SystemResourcesCounter(Time probeInterval) {
	probeIntervalMs = probeInterval.toMilliseconds();
	checkState(this.probeIntervalMs > 0);

	setName(SystemResourcesCounter.class.getSimpleName() + " probing thread");

	cpuUsagePerProcessor = new AtomicReferenceArray<>(hardwareAbstractionLayer.getProcessor().getLogicalProcessorCount());

	NetworkIF[] networkIFs = hardwareAbstractionLayer.getNetworkIFs();
	bytesReceivedPerInterface = new long[networkIFs.length];
	bytesSentPerInterface = new long[networkIFs.length];
	receiveRatePerInterface = new AtomicLongArray(networkIFs.length);
	sendRatePerInterface = new AtomicLongArray(networkIFs.length);
	networkInterfaceNames = new String[networkIFs.length];

	for (int i = 0; i < networkInterfaceNames.length; i++) {
		networkInterfaceNames[i] = networkIFs[i].getName();
	}
}
 
Example #9
Source File: AtomicLongArrayTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * repeated weakCompareAndSet succeeds in changing value when equal
 * to expected
 */
public void testWeakCompareAndSet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        do {} while (!aa.weakCompareAndSet(i, 1, 2));
        do {} while (!aa.weakCompareAndSet(i, 2, -4));
        assertEquals(-4, aa.get(i));
        do {} while (!aa.weakCompareAndSet(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}
 
Example #10
Source File: MpmcAtomicArrayQueue.java    From JCTools with Apache License 2.0 5 votes vote down vote up
private boolean notAvailable(long index, int mask, AtomicLongArray sBuffer, long expectedSeq) {
    final int seqOffset = calcCircularLongElementOffset(index, mask);
    final long seq = lvLongElement(sBuffer, seqOffset);
    if (seq < expectedSeq) {
        return true;
    }
    return false;
}
 
Example #11
Source File: AtomicLongArrayTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * getAndSet returns previous value and sets to given value at given index
 */
public void testGetAndSet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndSet(i, 0));
        assertEquals(0, aa.getAndSet(i, -10));
        assertEquals(-10, aa.getAndSet(i, 1));
    }
}
 
Example #12
Source File: AtomicDoubleArray.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Creates a new {@code AtomicDoubleArray} with the same length
 * as, and all elements copied from, the given array.
 *
 * @param array the array to copy elements from
 * @throws NullPointerException if array is null
 */


public AtomicDoubleArray(double[] array) {
  final int len = array.length;
  long[] longArray = new long[len];
  for (int i = 0; i < len; i++) {
    longArray[i] = doubleToRawLongBits(array[i]);
  }
  this.longs = new AtomicLongArray(longArray);
}
 
Example #13
Source File: HadoopConcurrentHashMultimap.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param tbl Table.
 */
private void incrementKeys(AtomicLongArray tbl) {
    locKeys.lazySet(locKeys.get() + 1);

    if (rnd.nextInt(tbl.length()) < 512)
        rehashIfNeeded(tbl);
}
 
Example #14
Source File: MpmcAtomicArrayQueue.java    From JCTools with Apache License 2.0 5 votes vote down vote up
@Override
public boolean offer(final E e) {
    if (null == e) {
        throw new NullPointerException();
    }
    final int mask = this.mask;
    final long capacity = mask + 1;
    final AtomicLongArray sBuffer = sequenceBuffer;
    long pIndex;
    int seqOffset;
    long seq;
    // start with bogus value, hope we don't need it
    long cIndex = Long.MIN_VALUE;
    do {
        pIndex = lvProducerIndex();
        seqOffset = calcCircularLongElementOffset(pIndex, mask);
        seq = lvLongElement(sBuffer, seqOffset);
        // consumer has not moved this seq forward, it's as last producer left
        if (seq < pIndex) {
            // Extra check required to ensure [Queue.offer == false iff queue is full]
            if (// test against cached cIndex
            pIndex - capacity >= cIndex && // test against latest cIndex
            pIndex - capacity >= (cIndex = lvConsumerIndex())) {
                return false;
            } else {
                // (+) hack to make it go around again without CAS
                seq = pIndex + 1;
            }
        }
    } while (// another producer has moved the sequence(or +)
    seq > pIndex || // failed to increment
    !casProducerIndex(pIndex, pIndex + 1));
    // casProducerIndex ensures correct construction
    spRefElement(buffer, calcCircularRefElementOffset(pIndex, mask), e);
    // seq++;
    soLongElement(sBuffer, seqOffset, pIndex + 1);
    return true;
}
 
Example #15
Source File: AtomicLongArrayTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * getAndAdd returns previous value and adds given value
 */
public void testGetAndAdd() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndAdd(i, 2));
        assertEquals(3, aa.get(i));
        assertEquals(3, aa.getAndAdd(i, -4));
        assertEquals(-1, aa.get(i));
    }
}
 
Example #16
Source File: AtomicDoubleArray.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Reconstitutes the instance from a stream (that is, deserializes it).
 */

private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
  s.defaultReadObject();

  // Read in array length and allocate array

  int length = s.readInt();
  this.longs = new AtomicLongArray(length);

  // Read in all elements in the proper order.
  for (int i = 0; i < length; i++) {
    set(i, s.readDouble());
  }
}
 
Example #17
Source File: ConcurrentBitSet.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public long[] toLongArray() {
  int bits = size();
  long[] result = new long[bits/BITS_PER_WORD];
  int i = 0;
  for (int b=0; b<bits;b += BITS_PER_WORD){
    AtomicLongArray array = arrays.get(arrayIndex(b));
    long word = array == null ? 0 : array.get(wordIndexInArray(b));
    result[i++] = word;
  }
  return result;
}
 
Example #18
Source File: UniformReservoir.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link UniformReservoir}.
 *
 * @param size the number of samples to keep in the sampling reservoir
 */
public UniformReservoir(int size) {
    this.values = new AtomicLongArray(size);
    for (int i = 0; i < values.length(); i++) {
        values.set(i, 0);
    }
    count.set(0);
}
 
Example #19
Source File: AtomicLongArrayTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * a deserialized serialized array holds same values
 */
public void testSerialization() throws Exception {
    AtomicLongArray x = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++)
        x.set(i, -i);
    AtomicLongArray y = serialClone(x);
    assertNotSame(x, y);
    assertEquals(x.length(), y.length());
    for (int i = 0; i < SIZE; i++) {
        assertEquals(x.get(i), y.get(i));
    }
}
 
Example #20
Source File: ThreadSafeBitSet.java    From zeno with Apache License 2.0 5 votes vote down vote up
private ThreadSafeBitSetSegments(int numSegments, int segmentLength) {
    AtomicLongArray segments[] = new AtomicLongArray[numSegments];

    for(int i=0;i<numSegments;i++) {
        segments[i] = new AtomicLongArray(segmentLength);
    }

    /// Thread safety: Because this.segments is final, the preceding operations in this constructor are guaranteed to be visible to any
    /// other thread which accesses this.segments.
    this.segments = segments;
}
 
Example #21
Source File: AtomicLongArrayTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * getAndIncrement returns previous value and increments
 */
public void testGetAndIncrement() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndIncrement(i));
        assertEquals(2, aa.get(i));
        aa.set(i, -2);
        assertEquals(-2, aa.getAndIncrement(i));
        assertEquals(-1, aa.getAndIncrement(i));
        assertEquals(0, aa.getAndIncrement(i));
        assertEquals(1, aa.get(i));
    }
}
 
Example #22
Source File: SpscLongArrayQueue.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
public boolean hasValue() {
    final AtomicLongArray a = buffer;
    final int m = mask;
    final long ci = a.get(1);

    int offset1 = calcOffset(ci + 1, m);
    return a.get(offset1) != 0L;
}
 
Example #23
Source File: ThreadSafeBitSet.java    From hollow with Apache License 2.0 5 votes vote down vote up
private ThreadSafeBitSetSegments(int numSegments, int segmentLength) {
    AtomicLongArray segments[] = new AtomicLongArray[numSegments];

    for(int i=0;i<numSegments;i++) {
        segments[i] = new AtomicLongArray(segmentLength);
    }

    /// Thread safety: Because this.segments is final, the preceding operations in this constructor are guaranteed to be visible to any
    /// other thread which accesses this.segments.
    this.segments = segments;
}
 
Example #24
Source File: AtomicLongArray9Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * repeated weakCompareAndSetAcquire succeeds in changing value when equal
 * to expected
 */
public void testWeakCompareAndSetAcquire() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        do {} while (!aa.weakCompareAndSetAcquire(i, 1, 2));
        do {} while (!aa.weakCompareAndSetAcquire(i, 2, -4));
        assertEquals(-4, aa.get(i));
        do {} while (!aa.weakCompareAndSetAcquire(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}
 
Example #25
Source File: AtomicLongArray9Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * repeated weakCompareAndSetPlain succeeds in changing value when equal
 * to expected
 */
public void testWeakCompareAndSetPlain() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        do {} while (!aa.weakCompareAndSetPlain(i, 1, 2));
        do {} while (!aa.weakCompareAndSetPlain(i, 2, -4));
        assertEquals(-4, aa.get(i));
        do {} while (!aa.weakCompareAndSetPlain(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}
 
Example #26
Source File: AtomicLongArray9Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * compareAndExchangeAcquire succeeds in changing value if equal to
 * expected else fails
 */
public void testCompareAndExchangeAcquire() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.compareAndExchangeAcquire(i, 1, 2));
        assertEquals(2, aa.compareAndExchangeAcquire(i, 2, -4));
        assertEquals(-4, aa.get(i));
        assertEquals(-4, aa.compareAndExchangeAcquire(i,-5, 7));
        assertEquals(-4, aa.get(i));
        assertEquals(-4, aa.compareAndExchangeAcquire(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}
 
Example #27
Source File: AtomicDoubleArray.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Creates a new {@code AtomicDoubleArray} with the same length
 * as, and all elements copied from, the given array.
 *
 * @param array the array to copy elements from
 * @throws NullPointerException if array is null
 */


public AtomicDoubleArray(double[] array) {
  final int len = array.length;
  long[] longArray = new long[len];
  for (int i = 0; i < len; i++) {
    longArray[i] = doubleToRawLongBits(array[i]);
  }
  this.longs = new AtomicLongArray(longArray);
}
 
Example #28
Source File: ParallelUnorderedSource.java    From reactive-streams-commons with Apache License 2.0 5 votes vote down vote up
void setupSubscribers() {
    int m = subscribers.length;
    
    for (int i = 0; i < m; i++) {
        if (cancelled) {
            return;
        }
        int j = i;

        SUBSCRIBER_COUNT.lazySet(this, i + 1);
        
        subscribers[i].onSubscribe(new Subscription() {
            @Override
            public void request(long n) {
                if (SubscriptionHelper.validate(n)) {
                    AtomicLongArray ra = requests;
                    for (;;) {
                        long r = ra.get(j);
                        if (r == Long.MAX_VALUE) {
                            return;
                        }
                        long u = BackpressureHelper.addCap(r, n);
                        if (ra.compareAndSet(j, r, u)) {
                            break;
                        }
                    }
                    if (subscriberCount == m) {
                        drain();
                    }
                }
            }
            
            @Override
            public void cancel() {
                ParallelDispatcher.this.cancel();
            }
        });
    }
}
 
Example #29
Source File: AtomicLongArray9Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * compareAndExchangeRelease succeeds in changing value if equal to
 * expected else fails
 */
public void testCompareAndExchangeRelease() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.compareAndExchangeRelease(i, 1, 2));
        assertEquals(2, aa.compareAndExchangeRelease(i, 2, -4));
        assertEquals(-4, aa.get(i));
        assertEquals(-4, aa.compareAndExchangeRelease(i,-5, 7));
        assertEquals(-4, aa.get(i));
        assertEquals(-4, aa.compareAndExchangeRelease(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}
 
Example #30
Source File: AtomicLongArray9Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * getOpaque returns the last value set
 */
public void testGetOpaqueSet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getOpaque(i));
        aa.set(i, 2);
        assertEquals(2, aa.getOpaque(i));
        aa.set(i, -3);
        assertEquals(-3, aa.getOpaque(i));
    }
}