@VisibleForTesting DecayingEstimatedHistogramReservoir(boolean considerZeroes, int bucketCount, Clock clock) { if (bucketCount == DEFAULT_BUCKET_COUNT) { if (considerZeroes == true) { bucketOffsets = DEFAULT_WITH_ZERO_BUCKET_OFFSETS; } else { bucketOffsets = DEFAULT_WITHOUT_ZERO_BUCKET_OFFSETS; } } else { bucketOffsets = EstimatedHistogram.newOffsets(bucketCount, considerZeroes); } decayingBuckets = new AtomicLongArray(bucketOffsets.length + 1); buckets = new AtomicLongArray(bucketOffsets.length + 1); this.clock = clock; decayLandmark = clock.getTime(); }
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException { SerializeWriter out = serializer.getWriter(); if (object != null) { AtomicLongArray array = (AtomicLongArray) object; int len = array.length(); out.append('['); for (int i = 0; i < len; i++) { long val = array.get(i); if (i != 0) { out.write(','); } out.writeLong(val); } out.append(']'); } else if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { out.write("[]"); } else { out.writeNull(); } }
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { SerializeWriter out = serializer.getWriter(); if (object == null) { if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { out.write("[]"); } else { out.writeNull(); } return; } AtomicLongArray array = (AtomicLongArray) object; int len = array.length(); out.append('['); for (int i = 0; i < len; ++i) { long val = array.get(i); if (i != 0) { out.write(','); } out.writeLong(val); } out.append(']'); }
@SuppressWarnings("unchecked") public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { if (parser.getLexer().token() == JSONToken.NULL) { parser.getLexer().nextToken(JSONToken.COMMA); return null; } JSONArray array = new JSONArray(); parser.parseArray(array); AtomicLongArray atomicArray = new AtomicLongArray(array.size()); for (int i = 0; i < array.size(); ++i) { atomicArray.set(i, array.getLong(i)); } return (T) atomicArray; }
/** * 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); } }
/** * 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)); }
/** * 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); }
/** * 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); }
public void set(int position) { int segmentPosition = position >>> log2SegmentSize; /// which segment -- div by num bits per segment int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits per segment int bitPosition = position & 0x3F; /// which bit in the long -- remainder of div by num bits in long (64) 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; } }
public void clear(int position) { int segmentPosition = position >>> log2SegmentSize; /// which segment -- div by num bits per segment int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits per segment int bitPosition = position & 0x3F; /// which bit in the long -- remainder of div by num bits in long (64) 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; } }
public long maxSetBit() { ThreadSafeBitSetSegments segments = this.segments.get(); int segmentIdx = segments.numSegments() - 1; for(;segmentIdx >= 0; segmentIdx--) { AtomicLongArray segment = segments.getSegment(segmentIdx); for(int longIdx=segment.length() - 1; longIdx >= 0; longIdx--) { long l = segment.get(longIdx); if(l != 0) return (segmentIdx << log2SegmentSize) + (longIdx * 64) + (63 - Long.numberOfLeadingZeros(l)); } } return -1; }
/** * Get the segment at <code>segmentIndex</code>. If this segment does not yet exist, create it. * * @param segmentIndex * @return */ 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); }
/** * 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; /// do not iterate over these values in the same order in which they appear in the hashed array. /// 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; }
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; }
/** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code ConcurrentBitSet} object that has * exactly the same set of bits set to {@code true} as this bit * set. That is, for every nonnegative {@code int} index {@code k}, * <pre>((ConcurrentBitSet)obj).get(k) == this.get(k)</pre> * must be true. The current sizes of the two bit sets are not compared. * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ @Override public boolean equals(Object obj) { if (!(obj instanceof ConcurrentBitSet)) { return false; } if (this == obj) { return true; } ConcurrentBitSet set = (ConcurrentBitSet)obj; for (int i = 0; i < arrays.length(); i++) { AtomicLongArray array1 = arrays.get(i); AtomicLongArray array2 = set.arrays.get(i); if (array1 == null && array2 == null) continue; int size = array1 == null ? array2.length() : array1.length(); for (int k=0; k<size;k++) { long word1 = array1 == null ? 0 : array1.get(k); long word2 = array2 == null ? 0 : array2.get(k); if (word1 != word2) return false; } } return true; }
public static void main(String[] args) { long[] data = new long[] { 1, 22, 333, 4444, 55555, 0, 1, 22, 333 }; AtomicLongArray ala = new AtomicLongArray(data); ExecutorService pool = Executors.newFixedThreadPool(3); for (int i = 0; i < 3; i++) { pool.execute(new Ato(ala)); } pool.shutdown(); for (int i = 0; i < ala.length(); i++) { System.out.print(ala.get(i) + " "); } }
public void test_AtomicLongArray() throws Exception { AtomicLongArray array = new AtomicLongArray(3); array.set(0, 1); array.set(1, 2); array.set(2, 3); String text = JSON.toJSONString(array); Assert.assertEquals("[1,2,3]", text); }
public HeapChunkSpace(final int initialCapacity, final int batchSize, final Graph p_graph, final boolean deepWorldPriority) { _interceptors = null; _batchSize = batchSize; _deep_priority = deepWorldPriority; _graph = p_graph; _maxEntries = initialCapacity; _hashEntries = initialCapacity * HASH_LOAD_FACTOR; _lru = new HeapFixedStack(initialCapacity, true); _dirtiesStack = new HeapFixedStack(initialCapacity, false); _hashNext = new AtomicIntegerArray(initialCapacity); _hash = new AtomicIntegerArray(_hashEntries); for (int i = 0; i < initialCapacity; i++) { _hashNext.set(i, -1); } for (int i = 0; i < _hashEntries; i++) { _hash.set(i, -1); } _chunkValues = new AtomicReferenceArray<Chunk>(initialCapacity); _chunkWorlds = new AtomicLongArray(_maxEntries); _chunkTimes = new AtomicLongArray(_maxEntries); _chunkIds = new AtomicLongArray(_maxEntries); _chunkTypes = new HeapAtomicByteArray(_maxEntries); _chunkMarks = new AtomicLongArray(_maxEntries); for (int i = 0; i < _maxEntries; i++) { _chunkMarks.set(i, 0); } }
private AtomicLongArray getArray(int index) { int arrayIndex = arrayIndex(index); if (size <= index) { synchronized(arrays) { if (size <= index) { size = index + 1; } } } if (arrayIndex < arrays.size()) return arrays.get(arrayIndex); synchronized(arrays) { while (arrays.size() <= arrayIndex) arrays.add(new AtomicLongArray(capacityStep)); } return arrays.get(arrayIndex); }
/** * Creates a new circular buffer with the specified capacity and initial value. * Any element whose value has not been explicitly set will have the initial value. * * @param capacity the length of the circular buffer * @param initialValue the initial value assumed by all elements */ public UnsafeCircularIntegerBuffer(int capacity, int initialValue) { long[] initialValues = new long[capacity]; for (int i = 0; i < capacity; i++) { initialValues[i] = getElement(i, initialValue); } _data = new AtomicLongArray(initialValues); _initialValue = initialValue; }
/** * 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); }
/** * 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()); } }
public ThreadStorage(int intSize, int longSize) { this.owner = Thread.currentThread(); if (intSize > 0) { this.intStore = new AtomicIntegerArray(intSize); } else { this.intStore = null; } if (longSize > 0) { this.longStore = new AtomicLongArray(longSize); } else { this.longStore = null; } }
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { if (parser.getLexer().token() == 8) { parser.getLexer().nextToken(16); return null; } Collection array = new JSONArray(); parser.parseArray(array); T atomicArray = new AtomicLongArray(array.size()); for (int i = 0; i < array.size(); i++) { atomicArray.set(i, array.getLong(i).longValue()); } return atomicArray; }
/** * 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)); }
/** * 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)); }
/** * 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)); }
/** * 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)); }
/** * 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), }; assertThrows(NullPointerException.class, throwingActions); }
/** * All Atomic updateAndGet methods throw NullPointerException on null function argument */ public void testUpdateAndGetNPE() { Runnable[] throwingActions = { () -> new AtomicLong().updateAndGet(null), () -> new AtomicInteger().updateAndGet(null), () -> new AtomicReference().updateAndGet(null), () -> new AtomicLongArray(1).updateAndGet(0, null), () -> new AtomicIntegerArray(1).updateAndGet(0, null), () -> new AtomicReferenceArray(1).updateAndGet(0, null), () -> aLongFieldUpdater().updateAndGet(this, null), () -> anIntFieldUpdater().updateAndGet(this, null), () -> anIntegerFieldUpdater().updateAndGet(this, null), }; assertThrows(NullPointerException.class, throwingActions); }
/** * All Atomic getAndAccumulate methods throw NullPointerException * on null function argument */ public void testGetAndAccumulateNPE() { Runnable[] throwingActions = { () -> new AtomicLong().getAndAccumulate(1L, null), () -> new AtomicInteger().getAndAccumulate(1, null), () -> new AtomicReference().getAndAccumulate(one, null), () -> new AtomicLongArray(1).getAndAccumulate(0, 1L, null), () -> new AtomicIntegerArray(1).getAndAccumulate(0, 1, null), () -> new AtomicReferenceArray(1).getAndAccumulate(0, one, null), () -> aLongFieldUpdater().getAndAccumulate(this, 1L, null), () -> anIntFieldUpdater().getAndAccumulate(this, 1, null), () -> anIntegerFieldUpdater().getAndAccumulate(this, one, null), }; assertThrows(NullPointerException.class, throwingActions); }
/** * All Atomic accumulateAndGet methods throw NullPointerException * on null function argument */ public void testAccumulateAndGetNPE() { Runnable[] throwingActions = { () -> new AtomicLong().accumulateAndGet(1L, null), () -> new AtomicInteger().accumulateAndGet(1, null), () -> new AtomicReference().accumulateAndGet(one, null), () -> new AtomicLongArray(1).accumulateAndGet(0, 1L, null), () -> new AtomicIntegerArray(1).accumulateAndGet(0, 1, null), () -> new AtomicReferenceArray(1).accumulateAndGet(0, one, null), () -> aLongFieldUpdater().accumulateAndGet(this, 1L, null), () -> anIntFieldUpdater().accumulateAndGet(this, 1, null), () -> anIntegerFieldUpdater().accumulateAndGet(this, one, null), }; assertThrows(NullPointerException.class, throwingActions); }
/** * getPlain returns the last value set */ public void testGetPlainSet() { AtomicLongArray aa = new AtomicLongArray(SIZE); for (int i = 0; i < SIZE; i++) { aa.set(i, 1); assertEquals(1, aa.getPlain(i)); aa.set(i, 2); assertEquals(2, aa.getPlain(i)); aa.set(i, -3); assertEquals(-3, aa.getPlain(i)); } }
/** * 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)); } }
/** * getAcquire returns the last value set */ public void testGetAcquireSet() { AtomicLongArray aa = new AtomicLongArray(SIZE); for (int i = 0; i < SIZE; i++) { aa.set(i, 1); assertEquals(1, aa.getAcquire(i)); aa.set(i, 2); assertEquals(2, aa.getAcquire(i)); aa.set(i, -3); assertEquals(-3, aa.getAcquire(i)); } }
/** * get returns the last value setPlain */ public void testGetSetPlain() { AtomicLongArray aa = new AtomicLongArray(SIZE); for (int i = 0; i < SIZE; i++) { aa.setPlain(i, 1); assertEquals(1, aa.get(i)); aa.setPlain(i, 2); assertEquals(2, aa.get(i)); aa.setPlain(i, -3); assertEquals(-3, aa.get(i)); } }
/** * get returns the last value setOpaque */ public void testGetSetOpaque() { AtomicLongArray aa = new AtomicLongArray(SIZE); for (int i = 0; i < SIZE; i++) { aa.setOpaque(i, 1); assertEquals(1, aa.get(i)); aa.setOpaque(i, 2); assertEquals(2, aa.get(i)); aa.setOpaque(i, -3); assertEquals(-3, aa.get(i)); } }
/** * get returns the last value setRelease */ public void testGetSetRelease() { AtomicLongArray aa = new AtomicLongArray(SIZE); for (int i = 0; i < SIZE; i++) { aa.setRelease(i, 1); assertEquals(1, aa.get(i)); aa.setRelease(i, 2); assertEquals(2, aa.get(i)); aa.setRelease(i, -3); assertEquals(-3, aa.get(i)); } }
/** * compareAndExchange succeeds in changing value if equal to * expected else fails */ public void testCompareAndExchange() { AtomicLongArray aa = new AtomicLongArray(SIZE); for (int i = 0; i < SIZE; i++) { aa.set(i, 1); assertEquals(1, aa.compareAndExchange(i, 1, 2)); assertEquals(2, aa.compareAndExchange(i, 2, -4)); assertEquals(-4, aa.get(i)); assertEquals(-4, aa.compareAndExchange(i,-5, 7)); assertEquals(-4, aa.get(i)); assertEquals(-4, aa.compareAndExchange(i, -4, 7)); assertEquals(7, aa.get(i)); } }