Java Code Examples for java.util.concurrent.ConcurrentHashMap#compute()

The following examples show how to use java.util.concurrent.ConcurrentHashMap#compute() . 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: FakeLockTest.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ConcurrentHashMap map = new ConcurrentHashMap();
    map.compute(1, (key, value) -> {
        map.remove(1);
        return 42;
    });
}
 
Example 2
Source File: AbstractConsoleEventBusListener.java    From buck with Apache License 2.0 5 votes vote down vote up
public static void aggregateStartedEvent(
    ConcurrentHashMap<EventKey, EventInterval> map, BuckEvent started) {
  map.compute(
      started.getEventKey(),
      (key, pair) ->
          pair == null
              ? EventInterval.start(started.getTimestampMillis())
              : pair.withStart(started.getTimestampMillis()));
}
 
Example 3
Source File: AbstractConsoleEventBusListener.java    From buck with Apache License 2.0 5 votes vote down vote up
public static void aggregateFinishedEvent(
    ConcurrentHashMap<EventKey, EventInterval> map, BuckEvent finished) {
  map.compute(
      finished.getEventKey(),
      (key, pair) ->
          pair == null
              ? EventInterval.finish(finished.getTimestampMillis())
              : pair.withFinish(finished.getTimestampMillis()));
}
 
Example 4
Source File: ConcurrentHashMap8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * compute does not replace if the function returns null
 */
public void testCompute() {
    ConcurrentHashMap map = map5();
    map.compute(six, (x, y) -> null);
    assertFalse(map.containsKey(six));
}
 
Example 5
Source File: ConcurrentHashMap8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * compute removes when the given key is present and function returns null
 */
public void testCompute4() {
    ConcurrentHashMap map = map5();
    map.compute(one, (x, y) -> null);
    assertFalse(map.containsKey(one));
}
 
Example 6
Source File: SerializedRequestHandlerTest.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 10000)
public void testCancellation() {
    final ConcurrentHashMap<String, List<Integer>> orderOfProcessing = new ConcurrentHashMap<>();

    SerializedRequestHandler<TestEvent> requestHandler = new SerializedRequestHandler<TestEvent>(executorService()) {
        @Override
        public CompletableFuture<Void> processEvent(TestEvent event) {
            orderOfProcessing.compute(event.getKey(), (x, y) -> {
                if (y == null) {
                    y = new ArrayList<>();
                }
                y.add(event.getNumber());
                return y;
            });
            return event.getFuture();
        }
    };

    String scope = "scope";
    String stream = "stream";
    List<Pair<TestEvent, CompletableFuture<Void>>> queue = requestHandler.getEventQueueForKey(getKeyForStream(scope, stream));
    assertNull(queue);
    AtomicBoolean stop = new AtomicBoolean(false);
    // post 3 work for stream
    TestEvent e1 = new TestEvent(scope, stream, 1);
    CompletableFuture<Void> p1 = requestHandler.process(e1, stop::get);
    TestEvent e2 = new TestEvent(scope, stream, 2);
    CompletableFuture<Void> p2 = requestHandler.process(e2, stop::get);
    TestEvent e3 = new TestEvent(scope, stream, 3);
    CompletableFuture<Void> p3 = requestHandler.process(e3, stop::get);

    queue = requestHandler.getEventQueueForKey(getKeyForStream(scope, stream));
    assertTrue(queue.size() >= 2);
    assertTrue(queue.stream().noneMatch(x -> x.getRight().isDone()));
    List<Integer> collect = queue.stream().map(x -> x.getLeft().getNumber()).collect(Collectors.toList());
    assertTrue(collect.indexOf(2) < collect.indexOf(3));
    
    // now set stop = true
    stop.set(true);
    
    // verify that until p1 completes nothing else will be processed. 
    queue = requestHandler.getEventQueueForKey(getKeyForStream(scope, stream));
    assertTrue(queue.size() >= 2);
    assertTrue(queue.stream().noneMatch(x -> x.getRight().isDone()));
    
    // now complete processing for event 1. All subsequent events for the stream will be cancelled.
    e1.complete();
    CompletableFuture.allOf(p1, p2, p3)
                     .exceptionally(e -> {
                         if (Exceptions.unwrap(e) instanceof CancellationException) {
                             return null;
                         } else {
                             throw new CompletionException(e);
                         }
                     })
                     .join();
    assertTrue(p1.isDone());
    assertTrue(p2.isCancelled());
    assertTrue(p3.isCancelled());
}
 
Example 7
Source File: ConcurrentHashMap8Test.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * compute does not replace if the function returns null
 */
public void testCompute() {
    ConcurrentHashMap map = map5();
    map.compute(six, (x, y) -> null);
    assertFalse(map.containsKey(six));
}
 
Example 8
Source File: ConcurrentHashMap8Test.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * compute removes when the given key is present and function returns null
 */
public void testCompute4() {
    ConcurrentHashMap map = map5();
    map.compute(one, (x, y) -> null);
    assertFalse(map.containsKey(one));
}
 
Example 9
Source File: TrimmedConfigurationCache.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to record the given key as the canonical invocation for its descriptor and the
 * passed-in trimmed configuration.
 *
 * <p>The trimmed configuration must be a subset of the input key's configuration. Otherwise,
 * {@link IllegalArgumentException} will be thrown.
 *
 * <p>If another key matching this configuration is found, that key will be returned. That key
 * represents the canonical invocation, which should produce the same result as the input key. It
 * may have been previously invalidated, but will be considered revalidated at this point.
 *
 * <p>Otherwise, if the input key is the first to trim to this configuration, the input key is
 * returned.
 */
public KeyT putIfAbsent(KeyT canonicalKey, ConfigurationT trimmedConfiguration) {
  ConfigurationT fullConfiguration = getConfigurationFor(canonicalKey);
  Preconditions.checkArgument(
      compareConfigurations(trimmedConfiguration, fullConfiguration).isSubsetOrEqual());
  ConcurrentHashMap<ConfigurationT, KeyAndState<KeyT>> trimmingsOfDescriptor =
      descriptors.computeIfAbsent(getDescriptorFor(canonicalKey), unused -> newDescriptorMap());
  KeyAndState<KeyT> currentMapping =
      trimmingsOfDescriptor.compute(
          trimmedConfiguration,
          (configuration, currentValue) -> {
            if (currentValue == null) {
              return KeyAndState.create(canonicalKey);
            } else {
              return currentValue.asValidated();
            }
          });
  boolean newlyAdded = currentMapping.getKey().equals(canonicalKey);
  int failedRemoves;
  do {
    failedRemoves = 0;
    for (Entry<ConfigurationT, KeyAndState<KeyT>> entry : trimmingsOfDescriptor.entrySet()) {
      if (entry.getValue().getState().equals(KeyAndState.State.POSSIBLY_INVALID)) {
        // Remove invalidated keys where:
        // * the same key evaluated to a different configuration than it does now
        // * (for trimmed configurations not yet seen) the new trimmed configuration has equal
        //   values for every fragment it shares with the old configuration (including subsets
        //   or supersets).
        // These are keys we know will not be revalidated as part of the current build.
        // Although it also ensures that we don't remove the entry we just added, the check for
        // invalidation is mainly to avoid wasting time checking entries that are still valid for
        // the current build and therefore will not match either of these properties.
        if (entry.getValue().getKey().equals(canonicalKey)
            || (newlyAdded
                && compareConfigurations(trimmedConfiguration, entry.getKey())
                    .hasEqualSharedFragments())) {
          if (!trimmingsOfDescriptor.remove(entry.getKey(), entry.getValue())) {
            // It's possible that this entry was removed by another thread in the meantime.
            failedRemoves += 1;
          }
        }
      }
    }
  } while (failedRemoves > 0);
  return currentMapping.getKey();
}