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

The following examples show how to use java.util.concurrent.ConcurrentHashMap#computeIfAbsent() . 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: DatabaseStringCodecImpl.java    From EasyTransaction with Apache License 2.0 6 votes vote down vote up
public DatabaseStringCodecImpl(String tablePrefix, DataSource dataSource, PlatformTransactionManager transManager) {
    this.dataSoruce = dataSource;
    this.jdbcTemplate = new JdbcTemplate(dataSource);
    this.transManager = transManager;
    
    tablePrefix = tablePrefix.trim();
    if(StringUtils.isNotBlank(tablePrefix)) {
        FIND_ID = addTablePrefix(tablePrefix, FIND_ID);
        INSERT_ID = addTablePrefix(tablePrefix, INSERT_ID);
        GET_MAX_ID_AND_LOCK = addTablePrefix(tablePrefix, GET_MAX_ID_AND_LOCK);
        GET_KEY_AND_LOCK = addTablePrefix(tablePrefix, GET_KEY_AND_LOCK);
        GET_ALL = addTablePrefix(tablePrefix, GET_ALL);
        GET_BY_ID = addTablePrefix(tablePrefix, GET_BY_ID);
    }
    
    List<DataObject> result = jdbcTemplate.query(GET_ALL, dataObjectMapper);
    for(DataObject data:result) {
        ConcurrentHashMap<String, Integer> typeValue2Key = vale2KeyMapping.computeIfAbsent(data.getTypeStr(), key->new ConcurrentHashMap<>());
        typeValue2Key.computeIfAbsent(data.getValueStr(), key->data.getKeyInt());
    }
    
}
 
Example 2
Source File: ConcurrentHashMap8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests performance of computeIfAbsent when the element is present.
 * See JDK-8161372
 * ant -Djsr166.tckTestClass=ConcurrentHashMapTest -Djsr166.methodFilter=testcomputeIfAbsent_performance -Djsr166.expensiveTests=true tck
 */
public void testcomputeIfAbsent_performance() {
    final int mapSize = 20;
    final int iterations = expensiveTests ? (1 << 23) : mapSize * 2;
    final int threads = expensiveTests ? 10 : 2;
    final ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
    for (int i = 0; i < mapSize; i++)
        map.put(i, i);
    final ExecutorService pool = Executors.newFixedThreadPool(2);
    try (PoolCleaner cleaner = cleaner(pool)) {
        Runnable r = new CheckedRunnable() {
            public void realRun() {
                int result = 0;
                for (int i = 0; i < iterations; i++)
                    result += map.computeIfAbsent(i % mapSize, k -> k + k);
                if (result == -42) throw new Error();
            }};
        for (int i = 0; i < threads; i++)
            pool.execute(r);
    }
}
 
Example 3
Source File: MapDeviceArrayFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected CallTarget createUncachedLoop(Object source, GrCUDAContext context) {
    ConcurrentHashMap<Class<?>, CallTarget> uncachedCallTargets = context.getMapCallTargets();
    DynamicDispatchLibrary dispatch = DynamicDispatchLibrary.getFactory().getUncached(source);
    Class<?> clazz = dispatch.dispatch(source);
    if (clazz == null) {
        clazz = source.getClass();
    }
    return uncachedCallTargets.computeIfAbsent(clazz, c -> Truffle.getRuntime().createCallTarget(new LoopRootNode(source, c)));
}
 
Example 4
Source File: CombinedRetentionProvider.java    From graphouse with Apache License 2.0 5 votes vote down vote up
private MetricRetention getOrMakeCombined(MetricRetentionConfig retention, MetricRetentionConfig aggregation) {
    String rRegexp = retention.getRegexp();
    String aRegexp = aggregation.getRegexp();
    ConcurrentHashMap<String, MetricRetention> subMap = combinedRetentions.computeIfAbsent(
        rRegexp, k -> new ConcurrentHashMap<>()
    );
    subMap.computeIfAbsent(aRegexp, k -> makeCombined(retention, aggregation));
    return subMap.get(aRegexp);
}
 
Example 5
Source File: DatabaseStringCodecImpl.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Override
public Integer findId(String stringType, String value) {

    ConcurrentHashMap<String, Integer> typeValue2Key = vale2KeyMapping.computeIfAbsent(stringType, key->new ConcurrentHashMap<>());
    int resultKey = typeValue2Key.computeIfAbsent(value, k->getOrInsertId(stringType,value));
    return resultKey;
}
 
Example 6
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleNamespaceTest() {
	Datastore databaseClient1 = mock(Datastore.class);
	Datastore databaseClient2 = mock(Datastore.class);

	AtomicInteger currentClient = new AtomicInteger(1);

	Supplier<Integer> regionProvider = currentClient::getAndIncrement;

	// this client selector will alternate between the two clients
	ConcurrentHashMap<Integer, Datastore> store = new ConcurrentHashMap<>();
	Supplier<Datastore> clientProvider = () -> store.computeIfAbsent(regionProvider.get(),
			u -> u % 2 == 1 ? databaseClient1 : databaseClient2);

	DatastoreTemplate template = new DatastoreTemplate(clientProvider,
			this.datastoreEntityConverter, new DatastoreMappingContext(),
			this.objectToKeyFactory);

	ChildEntity childEntity = new ChildEntity();
	childEntity.id = createFakeKey("key");

	when(this.objectToKeyFactory.getKeyFromObject(same(childEntity), any())).thenReturn(childEntity.id);

	// this first save should use the first client
	template.save(childEntity);
	verify(databaseClient1, times(1)).put((FullEntity<?>[]) any());
	verify(databaseClient2, times(0)).put((FullEntity<?>[]) any());

	// this second save should use the second client
	template.save(childEntity);
	verify(databaseClient1, times(1)).put((FullEntity<?>[]) any());
	verify(databaseClient2, times(1)).put((FullEntity<?>[]) any());

	// this third save should use the first client again
	template.save(childEntity);
	verify(databaseClient1, times(2)).put((FullEntity<?>[]) any());
	verify(databaseClient2, times(1)).put((FullEntity<?>[]) any());
}
 
Example 7
Source File: Java8Test.java    From Copiers with Apache License 2.0 5 votes vote down vote up
@Test
public void concurrentMap() {
    ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<>();
    map.computeIfAbsent("A", key -> value());
    map.computeIfAbsent("A", key -> value());
    map.computeIfAbsent("B", key -> value());
    System.out.println(map.size());
}
 
Example 8
Source File: ExpiringMap.java    From simplesource with Apache License 2.0 4 votes vote down vote up
final void insertIfAbsent(K k, Supplier<V> lazyV) {
    long outerKey = Instant.now(clock).getEpochSecond() / retentionInSeconds;
    ConcurrentHashMap<K, V> innerMap = outerMap.computeIfAbsent(outerKey, oKey -> new ConcurrentHashMap<>());
    innerMap.computeIfAbsent(k, ik -> lazyV.get());
}
 
Example 9
Source File: ConcurrentHashMap8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * computeIfAbsent adds when the given key is not present
 */
public void testComputeIfAbsent() {
    ConcurrentHashMap map = map5();
    map.computeIfAbsent(six, x -> "Z");
    assertTrue(map.containsKey(six));
}
 
Example 10
Source File: ConcurrentHashMap8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * computeIfAbsent does not add if function returns null
 */
public void testComputeIfAbsent3() {
    ConcurrentHashMap map = map5();
    map.computeIfAbsent(six, x -> null);
    assertFalse(map.containsKey(six));
}
 
Example 11
Source File: GcpDatastoreAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
private DatastoreProvider getDatastoreProvider(DatastoreNamespaceProvider keySupplier) {
	ConcurrentHashMap<String, Datastore> store = new ConcurrentHashMap<>();
	return () -> store.computeIfAbsent(keySupplier.get(), this::getDatastore);
}
 
Example 12
Source File: AbstractCache.java    From jetcache with Apache License 2.0 4 votes vote down vote up
static <K, V> V synchronizedLoad(CacheConfig config, AbstractCache<K,V> abstractCache,
                                 K key, Function<K, V> newLoader, Consumer<V> cacheUpdater) {
    ConcurrentHashMap<Object, LoaderLock> loaderMap = abstractCache.initOrGetLoaderMap();
    Object lockKey = buildLoaderLockKey(abstractCache, key);
    while (true) {
        boolean create[] = new boolean[1];
        LoaderLock ll = loaderMap.computeIfAbsent(lockKey, (unusedKey) -> {
            create[0] = true;
            LoaderLock loaderLock = new LoaderLock();
            loaderLock.signal = new CountDownLatch(1);
            loaderLock.loaderThread = Thread.currentThread();
            return loaderLock;
        });
        if (create[0] || ll.loaderThread == Thread.currentThread()) {
            try {
                V loadedValue = newLoader.apply(key);
                ll.success = true;
                ll.value = loadedValue;
                cacheUpdater.accept(loadedValue);
                return loadedValue;
            } finally {
                if (create[0]) {
                    ll.signal.countDown();
                    loaderMap.remove(lockKey);
                }
            }
        } else {
            try {
                Duration timeout = config.getPenetrationProtectTimeout();
                if (timeout == null) {
                    ll.signal.await();
                } else {
                    boolean ok = ll.signal.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
                    if(!ok) {
                        logger.info("loader wait timeout:" + timeout);
                        return newLoader.apply(key);
                    }
                }
            } catch (InterruptedException e) {
                logger.warn("loader wait interrupted");
                return newLoader.apply(key);
            }
            if (ll.success) {
                return (V) ll.value;
            } else {
                continue;
            }

        }
    }
}
 
Example 13
Source File: ConcurrentHashMap8Test.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * computeIfAbsent adds when the given key is not present
 */
public void testComputeIfAbsent() {
    ConcurrentHashMap map = map5();
    map.computeIfAbsent(six, (x) -> "Z");
    assertTrue(map.containsKey(six));
}
 
Example 14
Source File: ConcurrentHashMap8Test.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * computeIfAbsent does not add if function returns null
 */
public void testComputeIfAbsent3() {
    ConcurrentHashMap map = map5();
    map.computeIfAbsent(six, (x) -> null);
    assertFalse(map.containsKey(six));
}
 
Example 15
Source File: MoreFunctions.java    From buck with Apache License 2.0 4 votes vote down vote up
/** Thread-safe memoizer: computed value is cached and taken from cache on the second call. */
public static <A, B> Function<A, B> memoize(Function<A, B> function) {
  ConcurrentHashMap<A, B> map = new ConcurrentHashMap<>();
  return a -> map.computeIfAbsent(a, function);
}