java.util.concurrent.atomic.AtomicReferenceArray Java Examples

The following examples show how to use java.util.concurrent.atomic.AtomicReferenceArray. 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: MapMakerInternalMap.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Removes an entry whose key has been garbage collected.
 */
@CanIgnoreReturnValue
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
  lock();
  try {
    int newCount = count - 1;
    AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
    int index = hash & (table.length() - 1);
    ReferenceEntry<K, V> first = table.get(index);

    for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
      if (e == entry) {
        ++modCount;
        ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
        newCount = this.count - 1;
        table.set(index, newFirst);
        this.count = newCount; // write-volatile
        return true;
      }
    }

    return false;
  } finally {
    unlock();
  }
}
 
Example #2
Source File: TransportDfsOnlyAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected DfsOnlyResponse newResponse(DfsOnlyRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
    int successfulShards = 0;
    int failedShards = 0;
    List<ShardOperationFailedException> shardFailures = null;
    AtomicArray<DfsSearchResult> dfsResults = new AtomicArray<>(shardsResponses.length());
    for (int i = 0; i < shardsResponses.length(); i++) {
        Object shardResponse = shardsResponses.get(i);
        if (shardResponse == null) {
            // simply ignore non active shards
        } else if (shardResponse instanceof BroadcastShardOperationFailedException) {
            failedShards++;
            if (shardFailures == null) {
                shardFailures = new ArrayList<>();
            }
            shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
        } else {
            dfsResults.set(i, ((ShardDfsOnlyResponse) shardResponse).getDfsSearchResult());
            successfulShards++;
        }
    }
    AggregatedDfs dfs = searchPhaseController.aggregateDfs(dfsResults);
    return new DfsOnlyResponse(dfs, shardsResponses.length(), successfulShards, failedShards, shardFailures, buildTookInMillis(request));
}
 
Example #3
Source File: ConcurrentIntObjectHashMap.java    From reladomo with Apache License 2.0 6 votes vote down vote up
private void sequentialForEachKeyValue(IntObjectProcedure<V> block, AtomicReferenceArray currentArray, int start, int end)
{
    for (int i = start; i < end; i++)
    {
        Object o = currentArray.get(i);
        if (o == RESIZED || o == RESIZING)
        {
            throw new ConcurrentModificationException("can't iterate while resizing!");
        }
        Entry<V> e = (Entry<V>) o;
        while (e != null)
        {
            int key = e.getKey();
            Object value = e.getValue();
            block.value(key, (V) value);
            e = e.getNext();
        }
    }
}
 
Example #4
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@VisibleForTesting
@GuardedBy("this")
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
  int newCount = this.count - 1;
  AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
  int index = hash & (table.length() - 1);
  ReferenceEntry<K, V> first = table.get(index);
  for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
    if (e == entry) {
      ++modCount;
      ReferenceEntry<K, V> newFirst = removeValueFromChain(first, e, e.getKey(), hash, e.getValueReference().get(), e.getValueReference(), cause);
      newCount = this.count - 1;
      table.set(index, newFirst);
      this.count = newCount; // write-volatile
      return true;
    }
  }
  return false;
}
 
Example #5
Source File: MpscAtomicArrayQueue.java    From JCTools with Apache License 2.0 6 votes vote down vote up
@Override
public int drain(final Consumer<E> c, final int limit) {
    if (null == c)
        throw new IllegalArgumentException("c is null");
    if (limit < 0)
        throw new IllegalArgumentException("limit is negative: " + limit);
    if (limit == 0)
        return 0;
    final AtomicReferenceArray<E> buffer = this.buffer;
    final int mask = this.mask;
    final long cIndex = lpConsumerIndex();
    for (int i = 0; i < limit; i++) {
        final long index = cIndex + i;
        final int offset = calcCircularRefElementOffset(index, mask);
        final E e = lvRefElement(buffer, offset);
        if (null == e) {
            return i;
        }
        spRefElement(buffer, offset, null);
        // ordered store -> atomic and ordered for size()
        soConsumerIndex(index + 1);
        c.accept(e);
    }
    return limit;
}
 
Example #6
Source File: SystemResourcesCounter.java    From flink 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 #7
Source File: ConcurrentOffHeapWeakHolder.java    From reladomo with Apache License 2.0 6 votes vote down vote up
public ConcurrentOffHeapWeakHolder(int initialCapacity)
{
    if (initialCapacity < 0)
    {
        throw new IllegalArgumentException("Illegal Initial Capacity: " + initialCapacity);
    }
    if (initialCapacity > MAXIMUM_CAPACITY)
    {
        initialCapacity = MAXIMUM_CAPACITY;
    }

    int threshold = initialCapacity;
    threshold += threshold >> 1; // threshold = length * 0.75

    int capacity = 1;
    while (capacity < threshold)
    {
        capacity <<= 1;
    }
    if (capacity >= PARTITIONED_SIZE_THRESHOLD)
    {
        this.partitionedSize = new AtomicIntegerArray(SIZE_BUCKETS * 16); // we want 7 extra slots and 64 bytes for each slot. int is 4 bytes, so 64 bytes is 16 ints.
    }
    this.table = new AtomicReferenceArray(capacity + 1);
}
 
Example #8
Source File: MockKafkaProducer.java    From samza with Apache License 2.0 6 votes vote down vote up
public void run() {
  FutureTask[] callbackArray = new FutureTask[callbacksList.size()];
  AtomicReferenceArray<FutureTask> bufferList =
      new AtomicReferenceArray<FutureTask>(callbacksList.toArray(callbackArray));
  ExecutorService executor = Executors.newFixedThreadPool(10);
  try {
    for (int i = 0; i < bufferList.length(); i++) {
      Thread.sleep(sleepTime);
      FutureTask f = bufferList.get(i);
      if (!f.isDone()) {
        executor.submit(f).get();
      }
    }
  } catch (InterruptedException e) {
    e.printStackTrace();
  } catch (ExecutionException ee) {
    ee.printStackTrace();
  } finally {
    executor.shutdownNow();
  }
}
 
Example #9
Source File: ConcurrentHashMapV8.java    From thread_safe with Apache License 2.0 6 votes vote down vote up
/** Implementation for get and containsKey */
private final Object internalGet(Object k) {
    int h = spread(k.hashCode());
    retry: for (AtomicReferenceArray<Node> tab = table; tab != null;) {
        Node e, p; Object ek, ev; int eh;      // locals to read fields once
        for (e = tabAt(tab, (tab.length() - 1) & h); e != null; e = e.next) {
            if ((eh = e.hash) == MOVED) {
                if ((ek = e.key) instanceof TreeBin)  // search TreeBin
                    return ((TreeBin)ek).getValue(h, k);
                else {                        // restart with new table
                    tab = (AtomicReferenceArray<Node>)ek;
                    continue retry;
                }
            }
            else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
                    ((ek = e.key) == k || k.equals(ek)))
                return ev;
        }
        break;
    }
    return null;
}
 
Example #10
Source File: Binding.java    From datakernel with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <K> Binding<T> mapDependency(@NotNull Key<K> dependency, @NotNull Function<? super K, ? extends K> fn) {
	return new Binding<>(dependencies,
			(compiledBindings, threadsafe, scope, slot) ->
					compiler.compile(new CompiledBindingLocator() {
						@Override
						public @NotNull <Q> CompiledBinding<Q> get(Key<Q> key) {
							CompiledBinding<Q> originalBinding = compiledBindings.get(key);
							if (!key.equals(dependency)) return originalBinding;
							return new CompiledBinding<Q>() {
								@Nullable
								@Override
								public Q getInstance(AtomicReferenceArray[] scopedInstances, int synchronizedScope) {
									Q instance = originalBinding.getInstance(scopedInstances, synchronizedScope);
									return (Q) fn.apply((K) instance);
								}
							};
						}
					}, threadsafe, scope, slot), location);
}
 
Example #11
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * This method is a convenience for testing. Code should call {@link LocalCache#containsValue}
 * directly.
 */

@VisibleForTesting
boolean containsValue(Object value) {
  try {
    if (count != 0) { // read-volatile
      long now = map.ticker.read();
      AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
      int length = table.length();
      for (int i = 0; i < length; ++i) {
        for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
          V entryValue = getLiveValue(e, now);
          if (entryValue == null) {
            continue;
          }
          if (map.valueEquivalence.equivalent(value, entryValue)) {
            return true;
          }
        }
      }
    }
    return false;
  } finally {
    postReadCleanup();
  }
}
 
Example #12
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@VisibleForTesting
@GuardedBy("this")
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
  int newCount = this.count - 1;
  AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
  int index = hash & (table.length() - 1);
  ReferenceEntry<K, V> first = table.get(index);

  for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
    if (e == entry) {
      ++modCount;
      ReferenceEntry<K, V> newFirst =
          removeValueFromChain(
              first,
              e,
              e.getKey(),
              hash,
              e.getValueReference().get(),
              e.getValueReference(),
              cause);
      newCount = this.count - 1;
      table.set(index, newFirst);
      this.count = newCount; // write-volatile
      return true;
    }
  }

  return false;
}
 
Example #13
Source File: ArrayMap.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized V remove(int key) {
    AtomicReferenceArray<V> values = this.values;
    if (key < 0) {
        throw new IllegalArgumentException(negativeKey(key));
    } else if (key >= values.length()) {
        return null;
    } else {
        V oldValue = values.getAndSet(key, null);
        if (oldValue != null)
            SIZE_UPDATER.decrementAndGet(this); // Entry was there before, but now we're removing it
        return oldValue;
    }
}
 
Example #14
Source File: ResolveCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private <TRef extends PsiReference, TResult> Map<TRef, TResult> getMap(boolean physical, int index) {
  AtomicReferenceArray<Map> array = physical ? myPhysicalMaps : myNonPhysicalMaps;
  Map map = array.get(index);
  while (map == null) {
    Map newMap = createWeakMap();
    map = array.compareAndSet(index, null, newMap) ? newMap : array.get(index);
  }
  //noinspection unchecked
  return map;
}
 
Example #15
Source File: SpmcAtomicArrayQueue.java    From JCTools with Apache License 2.0 5 votes vote down vote up
@Override
public E relaxedPeek() {
    final AtomicReferenceArray<E> buffer = this.buffer;
    final int mask = this.mask;
    long currentConsumerIndex;
    long nextConsumerIndex = lvConsumerIndex();
    E e;
    do {
        currentConsumerIndex = nextConsumerIndex;
        e = lvRefElement(buffer, calcCircularRefElementOffset(currentConsumerIndex, mask));
        // sandwich the element load between 2 consumer index loads
        nextConsumerIndex = lvConsumerIndex();
    } while (nextConsumerIndex != currentConsumerIndex);
    return e;
}
 
Example #16
Source File: ConcurrentIntObjectHashMap.java    From reladomo with Apache License 2.0 5 votes vote down vote up
private void incrementSizeAndPossiblyResize(AtomicReferenceArray currentArray, int length, Object prev)
{
    this.addToSize(1);
    if (prev != null)
    {
        int localSize = this.size();
        int threshold = (length >> 1) + (length >> 2); // threshold = length * 0.75
        if (localSize + 1 > threshold)
        {
            this.resize(currentArray);
        }
    }
}
 
Example #17
Source File: AtomicReferenceArrayTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * getAndSet returns previous value and sets to given value at given index
 */
public void testGetAndSet() {
    AtomicReferenceArray aa = new AtomicReferenceArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, one);
        assertSame(one, aa.getAndSet(i, zero));
        assertSame(zero, aa.getAndSet(i, m10));
        assertSame(m10, aa.getAndSet(i, one));
    }
}
 
Example #18
Source File: AtomicReferenceArray9Test.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() {
    AtomicReferenceArray<Integer> aa = new AtomicReferenceArray<>(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, one);
        assertEquals(one, aa.getOpaque(i));
        aa.set(i, two);
        assertEquals(two, aa.getOpaque(i));
        aa.set(i, m3);
        assertEquals(m3, aa.getOpaque(i));
    }
}
 
Example #19
Source File: MulticastPublisher.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
MulticastPublisher(Publisher<T> original, int expectedSubscribers, int maxQueueSize, Executor executor) {
    super(executor);
    if (expectedSubscribers < 2) {
        throw new IllegalArgumentException("expectedSubscribers: " + expectedSubscribers + " (expected >=2)");
    }
    if (maxQueueSize < 1) {
        throw new IllegalArgumentException("maxQueueSize: " + maxQueueSize + " (expected >=1)");
    }
    this.original = original;
    notCancelledCount = expectedSubscribers;
    this.maxQueueSize = maxQueueSize;
    subscribers = new AtomicReferenceArray<>(expectedSubscribers);
}
 
Example #20
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
boolean removeLoadingValue(K key, int hash, LoadingValueReference<K, V> valueReference) {
  lock();
  try {
    AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
    int index = hash & (table.length() - 1);
    ReferenceEntry<K, V> first = table.get(index);
    for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
      K entryKey = e.getKey();
      if (e.getHash() == hash && entryKey != null
          && map.keyEquivalence.equivalent(key, entryKey)) {
        ValueReference<K, V> v = e.getValueReference();
        if (v == valueReference) {
          if (valueReference.isActive()) {
            e.setValueReference(valueReference.getOldValue());
          } else {
            ReferenceEntry<K, V> newFirst = removeEntryFromChain(first, e);
            table.set(index, newFirst);
          }
          return true;
        }
        return false;
      }
    }
    return false;
  } finally {
    unlock();
    postWriteCleanup();
  }
}
 
Example #21
Source File: TransportExistsAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected ExistsResponse newResponse(ExistsRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
    int successfulShards = 0;
    int failedShards = 0;
    boolean exists = false;
    List<ShardOperationFailedException> shardFailures = null;

    // if docs do exist, the last response will have exists = true (since we early terminate the shard requests)
    for (int i = shardsResponses.length() - 1; i >= 0 ; i--) {
        Object shardResponse = shardsResponses.get(i);
        if (shardResponse == null) {
            // simply ignore non active shards
        } else if (shardResponse instanceof BroadcastShardOperationFailedException) {
            failedShards++;
            if (shardFailures == null) {
                shardFailures = new ArrayList<>();
            }
            shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
        } else {
            successfulShards++;
            if ((exists = ((ShardExistsResponse) shardResponse).exists())) {
                successfulShards = shardsResponses.length() - failedShards;
                break;
            }
        }
    }
    return new ExistsResponse(exists, shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
 
Example #22
Source File: TransportSuggestAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected SuggestResponse newResponse(SuggestRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
    int successfulShards = 0;
    int failedShards = 0;

    final Map<String, List<Suggest.Suggestion>> groupedSuggestions = new HashMap<>();

    List<ShardOperationFailedException> shardFailures = null;
    for (int i = 0; i < shardsResponses.length(); i++) {
        Object shardResponse = shardsResponses.get(i);
        if (shardResponse == null) {
            // simply ignore non active shards
        } else if (shardResponse instanceof BroadcastShardOperationFailedException) {
            failedShards++;
            if (shardFailures == null) {
                shardFailures = new ArrayList<>();
            }
            shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
        } else {
            Suggest suggest = ((ShardSuggestResponse) shardResponse).getSuggest();
            Suggest.group(groupedSuggestions, suggest);
            successfulShards++;
        }
    }

    return new SuggestResponse(new Suggest(Suggest.reduce(groupedSuggestions)), shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
 
Example #23
Source File: MapMakerInternalMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Removes an entry whose value has been garbage collected.
 */

@CanIgnoreReturnValue
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
  lock();
  try {
    int newCount = this.count - 1;
    AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
    int index = hash & (table.length() - 1);
    ReferenceEntry<K, V> first = table.get(index);
    for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
      K entryKey = e.getKey();
      if (e.getHash() == hash && entryKey != null
          && map.keyEquivalence.equivalent(key, entryKey)) {
        ValueReference<K, V> v = e.getValueReference();
        if (v == valueReference) {
          ++modCount;
          ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
          newCount = this.count - 1;
          table.set(index, newFirst);
          this.count = newCount; // write-volatile
          return true;
        }
        return false;
      }
    }
    return false;
  } finally {
    unlock();
  }
}
 
Example #24
Source File: MapMakerInternalMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean containsValue(@Nullable Object value) {
  if (value == null) {
    return false;
  }

  // This implementation is patterned after ConcurrentHashMap, but without the locking. The only
  // way for it to return a false negative would be for the target value to jump around in the map
  // such that none of the subsequent iterations observed it, despite the fact that at every point
  // in time it was present somewhere int the map. This becomes increasingly unlikely as
  // CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible.
  final Segment<K, V>[] segments = this.segments;
  long last = -1L;
  for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) {
    long sum = 0L;
    for (Segment<K, V> segment : segments) {
      // ensure visibility of most recent completed write
      int unused = segment.count; // read-volatile
      AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table;
      for (int j = 0; j < table.length(); j++) {
        for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) {
          V v = segment.getLiveValue(e);
          if (v != null && valueEquivalence.equivalent(value, v)) {
            return true;
          }
        }
      }
      sum += segment.modCount;
    }
    if (sum == last) {
      break;
    }
    last = sum;
  }
  return false;
}
 
Example #25
Source File: Injector.java    From datakernel with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns a copy of the injector cache - a map of all already created non-transient instances at the current scope.
 */
public Map<Key<?>, Object> peekInstances() {
	Map<Key<?>, Object> result = new HashMap<>();
	AtomicReferenceArray scopeCache = scopeCaches[scopeCaches.length - 1];
	for (Entry<Key<?>, Integer> entry : localSlotMapping.entrySet()) {
		Object value = scopeCache.get(entry.getValue());
		if (value != null) {
			result.put(entry.getKey(), value);
		}
	}
	return result;
}
 
Example #26
Source File: MapMakerInternalMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Removes an entry whose value has been garbage collected.
 */

@CanIgnoreReturnValue
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
  lock();
  try {
    int newCount = this.count - 1;
    AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
    int index = hash & (table.length() - 1);
    ReferenceEntry<K, V> first = table.get(index);
    for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
      K entryKey = e.getKey();
      if (e.getHash() == hash && entryKey != null
          && map.keyEquivalence.equivalent(key, entryKey)) {
        ValueReference<K, V> v = e.getValueReference();
        if (v == valueReference) {
          ++modCount;
          ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
          newCount = this.count - 1;
          table.set(index, newFirst);
          this.count = newCount; // write-volatile
          return true;
        }
        return false;
      }
    }
    return false;
  } finally {
    unlock();
  }
}
 
Example #27
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void clear() {
  if (count != 0) { // read-volatile
    lock();
    try {
      long now = map.ticker.read();
      preWriteCleanup(now);
      AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
      for (int i = 0; i < table.length(); ++i) {
        for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
          // Loading references aren't actually in the map yet.
          if (e.getValueReference().isActive()) {
            K key = e.getKey();
            V value = e.getValueReference().get();
            RemovalCause cause = (key == null || value == null) ? RemovalCause.COLLECTED : RemovalCause.EXPLICIT;
            enqueueNotification(key, e.getHash(), value, e.getValueReference().getWeight(), cause);
          }
        }
      }
      for (int i = 0; i < table.length(); ++i) {
        table.set(i, null);
      }
      clearReferenceQueues();
      writeQueue.clear();
      accessQueue.clear();
      readCount.set(0);
      ++modCount;
      count = 0; // write-volatile
    } finally {
      unlock();
      postWriteCleanup();
    }
  }
}
 
Example #28
Source File: SpscLinkedArrayQueue.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
public SpscLinkedArrayQueue(final int bufferSize) {
    int p2capacity = SpscArrayQueue.roundToPowerOfTwo(Math.max(8, bufferSize));
    int mask = p2capacity - 1;
    AtomicReferenceArray<Object> buffer = new AtomicReferenceArray<>(p2capacity + 1);
    producerBuffer = buffer;
    producerMask = mask;
    adjustLookAheadStep(p2capacity);
    consumerBuffer = buffer;
    consumerMask = mask;
    producerLookAhead = mask - 1L; // we know it's all empty to start with
    soProducerIndex(0L);
}
 
Example #29
Source File: BaseMpscLinkedAtomicArrayQueue.java    From JCTools with Apache License 2.0 5 votes vote down vote up
private E newBufferPoll(AtomicReferenceArray<E> nextBuffer, long index) {
    final int offset = modifiedCalcCircularRefElementOffset(index, consumerMask);
    final E n = lvRefElement(nextBuffer, offset);
    if (n == null) {
        throw new IllegalStateException("new buffer must have at least one element");
    }
    soRefElement(nextBuffer, offset, null);
    soConsumerIndex(index + 2);
    return n;
}
 
Example #30
Source File: Atomic8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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),
    };
    assertThrows(NullPointerException.class, throwingActions);
}