java.util.concurrent.atomic.AtomicLongArray

Here are the examples of the java api class java.util.concurrent.atomic.AtomicLongArray taken from open source projects.

1. AtomicLongArrayTest#testCompareAndSetInMultipleThreads()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * 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));
}

2. ConcurrentBitSet#getWord()

Project: consulo
Source File: ConcurrentBitSet.java
View license
long getWord(int bitIndex) {
    if (bitIndex < 0) {
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
    }
    int arrayIndex = arrayIndex(bitIndex);
    AtomicLongArray array = arrays.get(arrayIndex);
    if (array == null) {
        return 0;
    }
    int wordIndexInArray = wordIndexInArray(bitIndex);
    return array.get(wordIndexInArray);
}

3. ConcurrentBitSet#getWord()

View license
long getWord(int bitIndex) {
    if (bitIndex < 0) {
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
    }
    int arrayIndex = arrayIndex(bitIndex);
    AtomicLongArray array = arrays.get(arrayIndex);
    if (array == null) {
        return 0;
    }
    int wordIndexInArray = wordIndexInArray(bitIndex);
    return array.get(wordIndexInArray);
}

4. AtomicLongArrayTest#testIncrementAndGet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * incrementAndGet increments and returns current value
     */
public void testIncrementAndGet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(2, aa.incrementAndGet(i));
        assertEquals(2, aa.get(i));
        aa.set(i, -2);
        assertEquals(-1, aa.incrementAndGet(i));
        assertEquals(0, aa.incrementAndGet(i));
        assertEquals(1, aa.incrementAndGet(i));
        assertEquals(1, aa.get(i));
    }
}

5. AtomicLongArrayTest#testCompareAndSet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * compareAndSet succeeds in changing value if equal to expected else fails
     */
public void testCompareAndSet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertTrue(aa.compareAndSet(i, 1, 2));
        assertTrue(aa.compareAndSet(i, 2, -4));
        assertEquals(-4, aa.get(i));
        assertFalse(aa.compareAndSet(i, -5, 7));
        assertEquals(-4, aa.get(i));
        assertTrue(aa.compareAndSet(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}

6. AtomicLongArrayTest#testGetAndIncrement()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * 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));
    }
}

7. AtomicLongArrayTest#testCountingInMultipleThreads()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * Multiple threads using same array of counters successfully
     * update a number of times equal to total count
     */
public void testCountingInMultipleThreads() throws InterruptedException {
    final AtomicLongArray aa = new AtomicLongArray(SIZE);
    long countdown = 10000;
    for (int i = 0; i < SIZE; i++) aa.set(i, countdown);
    Counter c1 = new Counter(aa);
    Counter c2 = new Counter(aa);
    Thread t1 = new Thread(c1);
    Thread t2 = new Thread(c2);
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    assertEquals(c1.counts + c2.counts, SIZE * countdown);
}

8. ConcurrentBitSet#changeWord()

View license
long changeWord(int bitIndex, @NotNull TLongFunction change) {
    if (bitIndex < 0) {
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
    }
    AtomicLongArray array = getOrCreateArray(bitIndex);
    int wordIndexInArray = wordIndexInArray(bitIndex);
    long word;
    long newWord;
    do {
        word = array.get(wordIndexInArray);
        newWord = change.execute(word);
    } while (!array.compareAndSet(wordIndexInArray, word, newWord));
    return word;
}

9. ByteArrayOrdinalMap#growKeyArray()

Project: zeno
Source File: ByteArrayOrdinalMap.java
View license
/**
     * Grow the key array.  All of the values in the current array must be re-hashed and added to the new array.
     */
private void growKeyArray() {
    AtomicLongArray newKeys = emptyKeyArray(pointersAndOrdinals.length() * 2);
    long valuesToAdd[] = new long[size];
    int counter = 0;
    /// if we do so, we cause large clusters of collisions to appear (because we resolve collisions with linear probing).
    for (int i = 0; i < pointersAndOrdinals.length(); i++) {
        long key = pointersAndOrdinals.get(i);
        if (key != EMPTY_BUCKET_VALUE) {
            valuesToAdd[counter++] = key;
        }
    }
    Arrays.sort(valuesToAdd);
    populateNewHashArray(newKeys, valuesToAdd);
    /// 70% load factor
    sizeBeforeGrow = (newKeys.length() * 7) / 10;
    pointersAndOrdinals = newKeys;
}

10. ConcurrentBitSet#changeWord()

Project: consulo
Source File: ConcurrentBitSet.java
View license
long changeWord(int bitIndex, @NotNull TLongFunction change) {
    if (bitIndex < 0) {
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
    }
    AtomicLongArray array = getOrCreateArray(bitIndex);
    int wordIndexInArray = wordIndexInArray(bitIndex);
    long word;
    long newWord;
    do {
        word = array.get(wordIndexInArray);
        newWord = change.execute(word);
    } while (!array.compareAndSet(wordIndexInArray, word, newWord));
    return word;
}

11. FastBlobTypeDeserializationState#populateFromByteOrdinalMap()

View license
/**
     * 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);
        }
    }
}

12. ThreadSafeBitSet#set()

Project: zeno
Source File: ThreadSafeBitSet.java
View license
public void set(int position) {
    /// which segment -- div by num bits per segment
    int segmentPosition = position >>> log2SegmentSize;
    /// which long in the segment -- remainder of div by num bits per segment
    int longPosition = (position >>> 6) & segmentMask;
    /// which bit in the long -- remainder of div by num bits in long (64)
    int bitPosition = position & 0x3F;
    AtomicLongArray segment = getSegment(segmentPosition);
    long mask = 1L << bitPosition;
    // Thread safety: we need to loop until we win the race to set the long value.
    while (true) {
        // determine what the new long value will be after we set the appropriate bit.
        long currentLongValue = segment.get(longPosition);
        long newLongValue = currentLongValue | mask;
        // if no other thread has modified the value since we read it, we won the race and we are done.
        if (segment.compareAndSet(longPosition, currentLongValue, newLongValue))
            break;
    }
}

13. AtomicLongArrayTest#testSerialization()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * 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));
    }
}

14. FastDateFormatTest#testParseSync()

View license
@Test
public void testParseSync() throws InterruptedException {
    final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    final SimpleDateFormat inner = new SimpleDateFormat(pattern);
    final Format sdf = new Format() {

        private static final long serialVersionUID = 1L;

        @Override
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition) {
            synchronized (this) {
                return inner.format(obj, toAppendTo, fieldPosition);
            }
        }

        @Override
        public Object parseObject(String source, ParsePosition pos) {
            synchronized (this) {
                return inner.parseObject(source, pos);
            }
        }
    };
    final AtomicLongArray sdfTime = measureTime(sdf, sdf);
    Format fdf = FastDateFormat.getInstance(pattern);
    final AtomicLongArray fdfTime = measureTime(fdf, fdf);
    System.out.println(">>FastDateFormatTest: FastDatePrinter:" + fdfTime.get(0) + "  SimpleDateFormat:" + sdfTime.get(0));
    System.out.println(">>FastDateFormatTest: FastDateParser:" + fdfTime.get(1) + "  SimpleDateFormat:" + sdfTime.get(1));
}

15. Atomic8Test#testLongArrayGetAndUpdate()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicLongArray getAndUpdate returns previous value and updates
     * result of supplied function
     */
public void testLongArrayGetAndUpdate() {
    AtomicLongArray a = new AtomicLongArray(1);
    a.set(0, 1);
    assertEquals(1L, a.getAndUpdate(0, Atomic8Test::addLong17));
    assertEquals(18L, a.getAndUpdate(0, Atomic8Test::addLong17));
    assertEquals(35L, a.get(0));
}

16. Atomic8Test#testLongArrayUpdateAndGet()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicLongArray updateAndGet updates with supplied function and
     * returns result.
     */
public void testLongArrayUpdateAndGet() {
    AtomicLongArray a = new AtomicLongArray(1);
    a.set(0, 1);
    assertEquals(18L, a.updateAndGet(0, Atomic8Test::addLong17));
    assertEquals(35L, a.updateAndGet(0, Atomic8Test::addLong17));
    assertEquals(35L, a.get(0));
}

17. Atomic8Test#testLongArrayGetAndAccumulate()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicLongArray getAndAccumulate returns previous value and updates
     * with supplied function.
     */
public void testLongArrayGetAndAccumulate() {
    AtomicLongArray a = new AtomicLongArray(1);
    a.set(0, 1);
    assertEquals(1L, a.getAndAccumulate(0, 2L, Long::sum));
    assertEquals(3L, a.getAndAccumulate(0, 3L, Long::sum));
    assertEquals(6L, a.get(0));
}

18. Atomic8Test#testLongArrayAccumulateAndGet()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicLongArray accumulateAndGet updates with supplied function and
     * returns result.
     */
public void testLongArrayAccumulateAndGet() {
    AtomicLongArray a = new AtomicLongArray(1);
    a.set(0, 1);
    assertEquals(7L, a.accumulateAndGet(0, 6L, Long::sum));
    assertEquals(10L, a.accumulateAndGet(0, 3L, Long::sum));
    assertEquals(10L, a.get(0));
}

19. ThreadSafeBitSet#orAll()

Project: zeno
Source File: ThreadSafeBitSet.java
View license
/**
     * Return a new bit set which contains all bits which are contained in *any* of the specified bit sets.
     *
     * @param bitSets
     * @return
     */
public static ThreadSafeBitSet orAll(ThreadSafeBitSet... bitSets) {
    if (bitSets.length == 0)
        return new ThreadSafeBitSet();
    int log2SegmentSize = bitSets[0].log2SegmentSize;
    int numLongsPerSegment = bitSets[0].numLongsPerSegment;
    ThreadSafeBitSetSegments segments[] = new ThreadSafeBitSetSegments[bitSets.length];
    int maxNumSegments = 0;
    for (int i = 0; i < bitSets.length; i++) {
        if (bitSets[i].log2SegmentSize != log2SegmentSize)
            throw new IllegalArgumentException("Segment sizes must be the same");
        segments[i] = bitSets[i].segments.get();
        if (segments[i].numSegments() > maxNumSegments)
            maxNumSegments = segments[i].numSegments();
    }
    ThreadSafeBitSetSegments newSegments = new ThreadSafeBitSetSegments(maxNumSegments, numLongsPerSegment);
    AtomicLongArray segment[] = new AtomicLongArray[segments.length];
    for (int i = 0; i < maxNumSegments; i++) {
        for (int j = 0; j < segments.length; j++) {
            segment[j] = i < segments[j].numSegments() ? segments[j].getSegment(i) : null;
        }
        AtomicLongArray newSegment = newSegments.getSegment(i);
        for (int j = 0; j < numLongsPerSegment; j++) {
            long value = 0;
            for (int k = 0; k < segments.length; k++) {
                if (segment[k] != null)
                    value |= segment[k].get(j);
            }
            newSegment.set(j, value);
        }
    }
    ThreadSafeBitSet or = new ThreadSafeBitSet(log2SegmentSize);
    or.segments.set(newSegments);
    return or;
}

20. AtomicLongArrayTest#testWeakCompareAndSet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * 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));
    }
}

21. AtomicLongArrayTest#testGetAndSet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * 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));
    }
}

22. AtomicLongArrayTest#testGetAndAdd()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * 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));
    }
}

23. AtomicLongArrayTest#testGetAndDecrement()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * getAndDecrement returns previous value and decrements
     */
public void testGetAndDecrement() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndDecrement(i));
        assertEquals(0, aa.getAndDecrement(i));
        assertEquals(-1, aa.getAndDecrement(i));
    }
}

24. ThreadSafeBitSet#get()

Project: zeno
Source File: ThreadSafeBitSet.java
View license
public boolean get(int position) {
    /// which segment -- div by num bits per segment
    int segmentPosition = position >>> log2SegmentSize;
    /// which long in the segment -- remainder of div by num bits per segment
    int longPosition = (position >>> 6) & segmentMask;
    /// which bit in the long -- remainder of div by num bits in long (64)
    int bitPosition = position & 0x3F;
    AtomicLongArray segment = getSegment(segmentPosition);
    long mask = 1L << bitPosition;
    return ((segment.get(longPosition) & mask) != 0);
}

25. AtomicLongArrayTest#testAddAndGet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * addAndGet adds given value to current, and returns current value
     */
public void testAddAndGet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(3, aa.addAndGet(i, 2));
        assertEquals(3, aa.get(i));
        assertEquals(-1, aa.addAndGet(i, -4));
        assertEquals(-1, aa.get(i));
    }
}

26. AtomicLongArrayTest#testDecrementAndGet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * decrementAndGet decrements and returns current value
     */
public void testDecrementAndGet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(0, aa.decrementAndGet(i));
        assertEquals(-1, aa.decrementAndGet(i));
        assertEquals(-2, aa.decrementAndGet(i));
        assertEquals(-2, aa.get(i));
    }
}

27. AtomicLongArrayTest#testConstructor2()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * constructor with array is of same size and has all elements
     */
public void testConstructor2() {
    long[] a = { 17L, 3L, -42L, 99L, -7L };
    AtomicLongArray aa = new AtomicLongArray(a);
    assertEquals(a.length, aa.length());
    for (int i = 0; i < a.length; i++) assertEquals(a[i], aa.get(i));
}

28. AtomicLongArrayTest#testToString()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * toString returns current value.
     */
public void testToString() {
    long[] a = { 17, 3, -42, 99, -7 };
    AtomicLongArray aa = new AtomicLongArray(a);
    assertEquals(Arrays.toString(a), aa.toString());
}

29. ByteArrayOrdinalMap#emptyKeyArray()

Project: zeno
Source File: ByteArrayOrdinalMap.java
View license
/**
     * Create an AtomicLongArray of the specified size, each value in the array will be EMPTY_BUCKET_VALUE
     */
private AtomicLongArray emptyKeyArray(int size) {
    AtomicLongArray arr = new AtomicLongArray(size);
    for (int i = 0; i < arr.length(); i++) {
        arr.set(i, EMPTY_BUCKET_VALUE);
    }
    return arr;
}

30. ConcurrentBitSet#nextClearBit()

View license
/**
  * Returns the index of the first bit that is set to {@code false}
  * that occurs on or after the specified starting index.
  *
  * @param fromIndex the index to start checking from (inclusive)
  * @return the index of the next clear bit
  * @throws IndexOutOfBoundsException if the specified index is negative
  */
public int nextClearBit(int fromIndex) {
    if (fromIndex < 0) {
        throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
    }
    int arrayIndex = arrayIndex(fromIndex);
    AtomicLongArray array = arrays.get(arrayIndex);
    int wordIndexInArray = wordIndexInArray(fromIndex);
    if (array == null) {
        return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD + (fromIndex % BITS_PER_WORD);
    }
    long word = ~array.get(wordIndexInArray) & (WORD_MASK << fromIndex);
    while (true) {
        if (word != 0) {
            return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD + Long.numberOfTrailingZeros(word);
        }
        if (++wordIndexInArray == array.length()) {
            wordIndexInArray = 0;
            if (++arrayIndex == arrays.length())
                return -1;
            array = arrays.get(arrayIndex);
            if (array == null) {
                return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD;
            }
        }
        word = ~array.get(wordIndexInArray);
    }
}

31. FastDateFormatTest#measureTime()

View license
private AtomicLongArray measureTime(final Format printer, final Format parser) throws InterruptedException {
    final ExecutorService pool = Executors.newFixedThreadPool(NTHREADS);
    final AtomicInteger failures = new AtomicInteger(0);
    final AtomicLongArray totalElapsed = new AtomicLongArray(2);
    for (int i = 0; i < NTHREADS; ++i) {
        pool.submit(new Runnable() {

            @Override
            public void run() {
                for (int j = 0; j < NROUNDS; ++j) {
                    try {
                        final Date date = new Date();
                        final long t0 = System.currentTimeMillis();
                        final String formattedDate = printer.format(date);
                        totalElapsed.addAndGet(0, System.currentTimeMillis() - t0);
                        final long t1 = System.currentTimeMillis();
                        final Object pd = parser.parseObject(formattedDate);
                        totalElapsed.addAndGet(1, System.currentTimeMillis() - t1);
                        if (!date.equals(pd)) {
                            failures.incrementAndGet();
                        }
                    } catch (final Exception e) {
                        failures.incrementAndGet();
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    pool.shutdown();
    // 30 seconds. Might need increase on very slow machines.
    if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
        pool.shutdownNow();
        fail("did not complete tasks");
    }
    assertEquals(0, failures.get());
    return totalElapsed;
}

32. ConcurrentBitSet#getOrCreateArray()

Project: consulo
Source File: ConcurrentBitSet.java
View license
@NotNull
private AtomicLongArray getOrCreateArray(int bitIndex) {
    int arrayIndex = arrayIndex(bitIndex);
    AtomicLongArray array;
    // while loop is here because of clear() method
    while ((array = arrays.get(arrayIndex)) == null) {
        arrays.compareAndSet(arrayIndex, null, new AtomicLongArray(1 << arrayIndex));
    }
    return array;
}

33. ConcurrentBitSet#nextSetBit()

Project: consulo
Source File: ConcurrentBitSet.java
View license
/**
   * Returns the index of the first bit that is set to {@code true}
   * that occurs on or after the specified starting index. If no such
   * bit exists then {@code -1} is returned.
   * <p/>
   * <p>To iterate over the {@code true} bits,
   * use the following loop:
   * <p/>
   * <pre> {@code
   * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
   *     // operate on index i here
   * }}</pre>
   *
   * @param fromIndex the index to start checking from (inclusive)
   * @return the index of the next set bit, or {@code -1} if there
   * is no such bit
   * @throws IndexOutOfBoundsException if the specified index is negative
   */
public int nextSetBit(int fromIndex) {
    if (fromIndex < 0) {
        throw new IndexOutOfBoundsException("bitIndex < 0: " + fromIndex);
    }
    int arrayIndex;
    AtomicLongArray array = null;
    for (arrayIndex = arrayIndex(fromIndex); arrayIndex < arrays.length() && (array = arrays.get(arrayIndex)) == null; arrayIndex++) ;
    if (array == null) {
        return -1;
    }
    int wordIndexInArray = wordIndexInArray(fromIndex);
    long word = array.get(wordIndexInArray) & (WORD_MASK << fromIndex);
    while (true) {
        if (word != 0) {
            return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD + Long.numberOfTrailingZeros(word);
        }
        if (++wordIndexInArray == array.length()) {
            wordIndexInArray = 0;
            for (++arrayIndex; arrayIndex != arrays.length() && (array = arrays.get(arrayIndex)) == null; arrayIndex++) ;
            if (array == null) {
                return -1;
            }
        }
        word = array.get(wordIndexInArray);
    }
}

34. ConcurrentBitSet#nextClearBit()

Project: consulo
Source File: ConcurrentBitSet.java
View license
/**
   * Returns the index of the first bit that is set to {@code false}
   * that occurs on or after the specified starting index.
   *
   * @param fromIndex the index to start checking from (inclusive)
   * @return the index of the next clear bit
   * @throws IndexOutOfBoundsException if the specified index is negative
   */
public int nextClearBit(int fromIndex) {
    if (fromIndex < 0) {
        throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
    }
    int arrayIndex = arrayIndex(fromIndex);
    AtomicLongArray array = arrays.get(arrayIndex);
    int wordIndexInArray = wordIndexInArray(fromIndex);
    if (array == null) {
        return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD + (fromIndex % BITS_PER_WORD);
    }
    long word = ~array.get(wordIndexInArray) & (WORD_MASK << fromIndex);
    while (true) {
        if (word != 0) {
            return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD + Long.numberOfTrailingZeros(word);
        }
        if (++wordIndexInArray == array.length()) {
            wordIndexInArray = 0;
            if (++arrayIndex == arrays.length())
                return -1;
            array = arrays.get(arrayIndex);
            if (array == null) {
                return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD;
            }
        }
        word = ~array.get(wordIndexInArray);
    }
}

35. HadoopConcurrentHashMultimap#visit()

View license
/**
     * Incrementally visits all the keys and values in the map.
     *
     * @param ignoreLastVisited Flag indicating that visiting must be started from the beginning.
     * @param v Visitor.
     * @return {@code false} If visiting was impossible due to rehashing.
     */
@Override
public boolean visit(boolean ignoreLastVisited, Visitor v) throws IgniteCheckedException {
    if (!state.compareAndSet(State.READING_WRITING, State.VISITING)) {
        assert state.get() != State.CLOSING;
        // Can not visit while rehashing happens.
        return false;
    }
    AtomicLongArray tbl0 = oldTbl;
    for (int i = 0; i < tbl0.length(); i++) {
        long meta = tbl0.get(i);
        while (meta != 0) {
            long valPtr = value(meta);
            long lastVisited = ignoreLastVisited ? 0 : lastVisitedValue(meta);
            if (valPtr != lastVisited) {
                v.onKey(key(meta), keySize(meta));
                // Set it to the first value in chain.
                lastVisitedValue(meta, valPtr);
                do {
                    v.onValue(valPtr + 12, valueSize(valPtr));
                    valPtr = nextValue(valPtr);
                } while (valPtr != lastVisited);
            }
            meta = collision(meta);
        }
    }
    state(State.VISITING, State.READING_WRITING);
    return true;
}

36. HadoopConcurrentHashMultimap#rehashIfNeeded()

View license
/**
     * @param fromTbl Table.
     */
private void rehashIfNeeded(AtomicLongArray fromTbl) {
    if (fromTbl.length() == Integer.MAX_VALUE)
        return;
    long keys0 = keys();
    if (// New size has to be >= than 3/4 of capacity to rehash.
    keys0 < 3 * (fromTbl.length() >>> 2))
        return;
    if (// Check if someone else have done the job.
    fromTbl != newTbl)
        return;
    if (!state.compareAndSet(State.READING_WRITING, State.REHASHING)) {
        // Visiting is allowed, but we will not rehash.
        assert state.get() != State.CLOSING;
        return;
    }
    if (fromTbl != newTbl) {
        // Double check.
        // Switch back.
        state(State.REHASHING, State.READING_WRITING);
        return;
    }
    // Calculate new table capacity.
    int newLen = fromTbl.length();
    do {
        newLen <<= 1;
    } while (newLen < keys0);
    if (// Still more than 3/4.
    keys0 >= 3 * (newLen >>> 2))
        newLen <<= 1;
    // This is our target table for rehashing.
    AtomicLongArray toTbl = new AtomicLongArray(newLen);
    // Make the new table visible before rehashing.
    newTbl = toTbl;
    // Rehash.
    int newMask = newLen - 1;
    long failedMeta = 0;
    GridLongList collisions = new GridLongList(16);
    for (int i = 0; i < fromTbl.length(); i++) {
        // Scan source table.
        long meta = fromTbl.get(i);
        assert meta != -1;
        if (meta == 0) {
            // No entry.
            failedMeta = 0;
            if (// Mark as moved.
            !fromTbl.compareAndSet(i, 0, -1))
                // Retry.
                i--;
            continue;
        }
        do {
            // Collect all the collisions before the last one failed to nullify or 0.
            collisions.add(meta);
            meta = collision(meta);
        } while (meta != failedMeta);
        do {
            // Go from the last to the first to avoid 'in-flight' state for meta entries.
            meta = collisions.remove();
            int addr = keyHash(meta) & newMask;
            for (; ; ) {
                // Move meta entry to the new table.
                long toCollision = toTbl.get(addr);
                collision(meta, toCollision);
                if (toTbl.compareAndSet(addr, toCollision, meta))
                    break;
            }
        } while (!collisions.isEmpty());
        // Here 'meta' will be a root pointer in old table.
        if (!fromTbl.compareAndSet(i, meta, -1)) {
            // Try to mark as moved.
            failedMeta = meta;
            // Retry the same address in table because new keys were added.
            i--;
        } else
            failedMeta = 0;
    }
    // Now old and new tables will be the same again.
    oldTbl = toTbl;
    state(State.REHASHING, State.READING_WRITING);
}

37. ConcurrentBitSet#getOrCreateArray()

View license
@NotNull
private AtomicLongArray getOrCreateArray(int bitIndex) {
    int arrayIndex = arrayIndex(bitIndex);
    AtomicLongArray array;
    // while loop is here because of clear() method
    while ((array = arrays.get(arrayIndex)) == null) {
        arrays.compareAndSet(arrayIndex, null, new AtomicLongArray(1 << arrayIndex));
    }
    return array;
}

38. ConcurrentBitSet#nextSetBit()

View license
/**
  * Returns the index of the first bit that is set to {@code true}
  * that occurs on or after the specified starting index. If no such
  * bit exists then {@code -1} is returned.
  * <p/>
  * <p>To iterate over the {@code true} bits,
  * use the following loop:
  * <p/>
  * <pre> {@code
  * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
  *     // operate on index i here
  * }}</pre>
  *
  * @param fromIndex the index to start checking from (inclusive)
  * @return the index of the next set bit, or {@code -1} if there
  * is no such bit
  * @throws IndexOutOfBoundsException if the specified index is negative
  */
public int nextSetBit(int fromIndex) {
    if (fromIndex < 0) {
        throw new IndexOutOfBoundsException("bitIndex < 0: " + fromIndex);
    }
    int arrayIndex;
    AtomicLongArray array = null;
    for (arrayIndex = arrayIndex(fromIndex); arrayIndex < arrays.length() && (array = arrays.get(arrayIndex)) == null; arrayIndex++) ;
    if (array == null) {
        return -1;
    }
    int wordIndexInArray = wordIndexInArray(fromIndex);
    long word = array.get(wordIndexInArray) & (WORD_MASK << fromIndex);
    while (true) {
        if (word != 0) {
            return ((1 << arrayIndex) - 1 + wordIndexInArray) * BITS_PER_WORD + Long.numberOfTrailingZeros(word);
        }
        if (++wordIndexInArray == array.length()) {
            wordIndexInArray = 0;
            for (++arrayIndex; arrayIndex != arrays.length() && (array = arrays.get(arrayIndex)) == null; arrayIndex++) ;
            if (array == null) {
                return -1;
            }
        }
        word = array.get(wordIndexInArray);
    }
}

39. AtomicLongArrayTest#testGetLazySet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * get returns the last value lazySet at index by same thread
     */
public void testGetLazySet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.lazySet(i, 1);
        assertEquals(1, aa.get(i));
        aa.lazySet(i, 2);
        assertEquals(2, aa.get(i));
        aa.lazySet(i, -3);
        assertEquals(-3, aa.get(i));
    }
}

40. MpmcAtomicArrayQueue#offer()

Project: JCTools
Source File: MpmcAtomicArrayQueue.java
View license
@Override
public boolean offer(final E e) {
    if (null == e) {
        throw new NullPointerException();
    }
    // local load of field to avoid repeated loads after volatile reads
    final int mask = this.mask;
    final int capacity = mask + 1;
    final AtomicLongArray sBuffer = sequenceBuffer;
    long currentProducerIndex;
    int seqOffset;
    // start with bogus value, hope we don't need it
    long cIndex = Long.MAX_VALUE;
    while (true) {
        // LoadLoad
        currentProducerIndex = lvProducerIndex();
        seqOffset = calcSequenceOffset(currentProducerIndex, mask);
        // LoadLoad
        final long seq = lvSequence(sBuffer, seqOffset);
        final long delta = seq - currentProducerIndex;
        if (delta == 0) {
            // this is expected if we see this first time around
            if (casProducerIndex(currentProducerIndex, currentProducerIndex + 1)) {
                // Successful CAS: full barrier
                break;
            }
        // failed cas, retry 1
        } else if (// poll has not moved this value forward
        delta < 0 && // test against cached cIndex
        currentProducerIndex - capacity <= cIndex && currentProducerIndex - capacity <= (cIndex = lvConsumerIndex())) {
            // Extra check required to ensure [Queue.offer == false iff queue is full]
            return false;
        }
    // another producer has moved the sequence by one, retry 2
    }
    // on 64bit(no compressed oops) JVM this is the same as seqOffset
    final int elementOffset = calcElementOffset(currentProducerIndex, mask);
    spElement(elementOffset, e);
    // increment sequence by 1, the value expected by consumer
    // (seeing this value from a producer will lead to retry 2)
    // StoreStore
    soSequence(sBuffer, seqOffset, currentProducerIndex + 1);
    return true;
}

41. MpmcAtomicArrayQueue#poll()

Project: JCTools
Source File: MpmcAtomicArrayQueue.java
View license
/**
     * {@inheritDoc}
     * <p>
     * Because return null indicates queue is empty we cannot simply rely on next element visibility for poll
     * and must test producer index when next element is not visible.
     */
@Override
public E poll() {
    // local load of field to avoid repeated loads after volatile reads
    final AtomicLongArray lSequenceBuffer = sequenceBuffer;
    final int mask = this.mask;
    long currentConsumerIndex;
    int seqOffset;
    // start with bogus value, hope we don't need it
    long pIndex = -1;
    while (true) {
        // LoadLoad
        currentConsumerIndex = lvConsumerIndex();
        seqOffset = calcSequenceOffset(currentConsumerIndex, mask);
        // LoadLoad
        final long seq = lvSequence(lSequenceBuffer, seqOffset);
        final long delta = seq - (currentConsumerIndex + 1);
        if (delta == 0) {
            if (casConsumerIndex(currentConsumerIndex, currentConsumerIndex + 1)) {
                // Successful CAS: full barrier
                break;
            }
        // failed cas, retry 1
        } else if (// slot has not been moved by producer
        delta < 0 && // test against cached pIndex
        currentConsumerIndex >= pIndex && currentConsumerIndex == (pIndex = lvProducerIndex())) {
            // strict empty check, this ensures [Queue.poll() == null iff isEmpty()]
            return null;
        }
    // another consumer beat us and moved sequence ahead, retry 2
    }
    // on 64bit(no compressed oops) JVM this is the same as seqOffset
    final int offset = calcElementOffset(currentConsumerIndex, mask);
    final E e = lpElement(offset);
    spElement(offset, null);
    // Move sequence ahead by capacity, preparing it for next offer
    // (seeing this value from a consumer will lead to retry 2)
    // StoreStore
    soSequence(lSequenceBuffer, seqOffset, currentConsumerIndex + mask + 1);
    return e;
}

42. HamerlyKMeans#cluster()

Project: JSAT
Source File: HamerlyKMeans.java
View license
//TODO reduce some code duplication in the methods bellow 
@Override
protected double cluster(final DataSet dataSet, List<Double> accelCache, final int k, final List<Vec> means, final int[] assignment, final boolean exactTotal, ExecutorService threadpool, boolean returnError) {
    final int N = dataSet.getSampleSize();
    final int D = dataSet.getNumNumericalVars();
    TrainableDistanceMetric.trainIfNeeded(dm, dataSet, threadpool);
    final List<Vec> X = dataSet.getDataVectors();
    //used like htis b/c we want it final for convinence, but input may be null
    final List<Double> distAccel;
    if (accelCache == null) {
        if (threadpool == null || threadpool instanceof FakeExecutor)
            distAccel = dm.getAccelerationCache(X);
        else
            distAccel = dm.getAccelerationCache(X, threadpool);
    } else
        distAccel = accelCache;
    final List<List<Double>> meanQI = new ArrayList<List<Double>>(k);
    if (means.size() != k) {
        means.clear();
        if (threadpool == null || threadpool instanceof FakeExecutor)
            means.addAll(selectIntialPoints(dataSet, k, dm, distAccel, rand, seedSelection));
        else
            means.addAll(selectIntialPoints(dataSet, k, dm, distAccel, rand, seedSelection, threadpool));
    }
    //Make our means dense
    for (int i = 0; i < means.size(); i++) if (means.get(i).isSparse())
        means.set(i, new DenseVector(means.get(i)));
    /**
         * vector sum of all points in cluster j <br>
         * denoted c'(j)
         */
    final Vec[] cP = new Vec[k];
    final Vec[] tmpVecs = new Vec[k];
    /**
         * number of points assigned to cluster j,<br>
         * denoted q(j)
         */
    final AtomicLongArray q = new AtomicLongArray(k);
    /**
         * distance that c(j) last moved <br>
         * denoted p(j)
         */
    final double[] p = new double[k];
    /**
         * distance from c(j) to its closest other center.<br>
         * denoted s(j)
         */
    final double[] s = new double[k];
    //index of the center to which x(i) is assigned
    //use assignment array
    /**
         * upper bound on the distance between x(i) and its assigned center c(a(i)) <br>
         * denoted u(i)
         */
    final double[] u = new double[N];
    /**
         * lower bound on the distance between x(i) and its second closest 
         * center  that is, the closest center to x(i) that is not c(a(i)) <br>
         * denoted l(i)
         */
    final double[] l = new double[N];
    final ThreadLocal<Vec[]> localDeltas = new ThreadLocal<Vec[]>() {

        @Override
        protected Vec[] initialValue() {
            Vec[] toRet = new Vec[means.size()];
            for (int i = 0; i < k; i++) toRet[i] = new DenseVector(D);
            return toRet;
        }
    };
    //Start of algo
    Initialize(dataSet, q, means, tmpVecs, cP, u, l, assignment, threadpool, localDeltas, X, distAccel, meanQI);
    //Use dense mean objects
    for (int i = 0; i < means.size(); i++) if (means.get(i).isSparse())
        means.set(i, new DenseVector(means.get(i)));
    final AtomicInteger updates = new AtomicInteger(N);
    while (updates.get() > 0) {
        moveCenters(means, tmpVecs, cP, q, p, meanQI);
        UpdateBounds(p, assignment, u, l);
        updates.set(0);
        updateS(s, means, threadpool, meanQI);
        if (threadpool == null) {
            int localUpdates = 0;
            for (int i = 0; i < N; i++) {
                localUpdates += mainLoopWork(dataSet, i, s, assignment, u, l, q, cP, X, distAccel, means, meanQI);
            }
            updates.set(localUpdates);
        } else {
            final CountDownLatch latch = new CountDownLatch(SystemInfo.LogicalCores);
            for (int id = 0; id < SystemInfo.LogicalCores; id++) {
                final int ID = id;
                threadpool.submit(new Runnable() {

                    @Override
                    public void run() {
                        Vec[] deltas = localDeltas.get();
                        int localUpdates = 0;
                        for (int i = ID; i < N; i += SystemInfo.LogicalCores) {
                            localUpdates += mainLoopWork(dataSet, i, s, assignment, u, l, q, deltas, X, distAccel, means, meanQI);
                        }
                        //collect deltas
                        if (localUpdates > 0) {
                            updates.getAndAdd(localUpdates);
                            for (int i = 0; i < cP.length; i++) {
                                synchronized (cP[i]) {
                                    cP[i].mutableAdd(deltas[i]);
                                }
                                deltas[i].zeroOut();
                            }
                        }
                        latch.countDown();
                    }
                });
            }
            try {
                latch.await();
            } catch (InterruptedException ex) {
                Logger.getLogger(HamerlyKMeans.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    if (returnError) {
        double totalDistance = 0;
        if (saveCentroidDistance)
            nearestCentroidDist = new double[N];
        else
            nearestCentroidDist = null;
        if (exactTotal == true)
            for (int i = 0; i < N; i++) {
                double dist = dm.dist(i, means.get(assignment[i]), meanQI.get(assignment[i]), X, distAccel);
                totalDistance += Math.pow(dist, 2);
                if (saveCentroidDistance)
                    nearestCentroidDist[i] = dist;
            }
        else
            for (int i = 0; i < N; i++) {
                totalDistance += Math.pow(u[i], 2);
                if (saveCentroidDistance)
                    nearestCentroidDist[i] = u[i];
            }
        return totalDistance;
    } else
        //who cares
        return 0;
}

43. Lazy#main()

Project: openjdk
Source File: Lazy.java
View license
public static void main(String[] args) throws Exception {
    final AtomicBoolean b = new AtomicBoolean();
    final AtomicInteger i = new AtomicInteger();
    final AtomicLong l = new AtomicLong();
    final AtomicReference<Long> r = new AtomicReference<Long>();
    final AtomicIntegerArray ia = new AtomicIntegerArray(1);
    final AtomicLongArray la = new AtomicLongArray(1);
    final AtomicReferenceArray<Long> ra = new AtomicReferenceArray<Long>(1);
    final AtomicIntegerFieldUpdater<Lazy> iu = AtomicIntegerFieldUpdater.newUpdater(Lazy.class, "ii");
    final AtomicLongFieldUpdater<Lazy> lu = AtomicLongFieldUpdater.newUpdater(Lazy.class, "ll");
    final AtomicReferenceFieldUpdater<Lazy, Boolean> ru = AtomicReferenceFieldUpdater.newUpdater(Lazy.class, Boolean.class, "bb");
    Thread[] threads = { new Thread() {

        public void run() {
            b.lazySet(true);
        }
    }, new Thread() {

        public void run() {
            i.lazySet(2);
        }
    }, new Thread() {

        public void run() {
            l.lazySet(3L);
        }
    }, new Thread() {

        public void run() {
            r.lazySet(9L);
        }
    }, new Thread() {

        public void run() {
            ia.lazySet(0, 4);
        }
    }, new Thread() {

        public void run() {
            la.lazySet(0, 5L);
        }
    }, new Thread() {

        public void run() {
            ra.lazySet(0, 6L);
        }
    }, new Thread() {

        public void run() {
            iu.lazySet(z, 7);
        }
    }, new Thread() {

        public void run() {
            lu.lazySet(z, 8L);
        }
    }, new Thread() {

        public void run() {
            ru.lazySet(z, true);
        }
    } };
    for (Thread t : threads) t.start();
    for (Thread t : threads) t.join();
    if (!(b.get() == true && i.get() == 2 && l.get() == 3L && r.get() == 9L && ia.get(0) == 4 && la.get(0) == 5L && ra.get(0) == 6L && z.ii == 7 && z.ll == 8L && z.bb == true))
        throw new Exception("lazySet failed");
}

44. AtomicLongArrayTest#testConstructor()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * constructor creates array of given size with all elements zero
     */
public void testConstructor() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) assertEquals(0, aa.get(i));
}

45. AtomicLongArrayTest#testIndexing()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * 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 }) {
        try {
            aa.get(index);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.set(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.lazySet(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.compareAndSet(index, 1, 2);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.weakCompareAndSet(index, 1, 2);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.getAndAdd(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.addAndGet(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
    }
}

46. AtomicLongArrayTest#testGetSet()

Project: openjdk
Source File: AtomicLongArrayTest.java
View license
/**
     * get returns the last value set at index
     */
public void testGetSet() {
    AtomicLongArray aa = new AtomicLongArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.get(i));
        aa.set(i, 2);
        assertEquals(2, aa.get(i));
        aa.set(i, -3);
        assertEquals(-3, aa.get(i));
    }
}