Java Code Examples for java.util.concurrent.ConcurrentMap#computeIfAbsent()
The following examples show how to use
java.util.concurrent.ConcurrentMap#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: AbstractHubDriver.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public void start(Map<String,String> restore, State curState) { ConcurrentMap<Version,Map<String,Class<?>>> dconvs = conversions.computeIfAbsent(getDriverName(), (k) -> new ConcurrentHashMap<>()); Map<String,Class<?>> convs = dconvs.computeIfAbsent(getDriverVersion(), (v) -> new ConcurrentHashMap<>()); for (Map.Entry<String,String> entry : restore.entrySet()) { Class<?> type = convs.get(entry.getKey()); if (type == null) { log.warn("cannot restore driver state {} for driver {} {}: data type not registered", entry.getKey(), getDriverName(), getDriverVersion()); continue; } Object value = ConversionService.to(type, entry.getValue()); state.put(entry.getKey(), value); if (log.isTraceEnabled()) { log.trace("restore driver state {}={} for driver {} {}", entry.getKey(), value, getDriverName(), getDriverVersion()); } } super.start(curState); start(); }
Example 2
Source File: MicrometerUtil.java From armeria with Apache License 2.0 | 6 votes |
private static <T> Object register(ConcurrentMap<MeterIdPrefix, Object> map, RegistrationState registrationState, MeterRegistry registry, MeterIdPrefix idPrefix, Class<T> type, BiFunction<MeterRegistry, MeterIdPrefix, T> factory) { final Object object = map.computeIfAbsent(idPrefix, i -> { registrationState.isRegistering = true; try { return factory.apply(registry, i); } finally { registrationState.isRegistering = false; } }); if (!type.isInstance(object)) { throw new IllegalStateException( "An object of different type has been registered already for idPrefix: " + idPrefix + " (expected: " + type.getName() + ", actual: " + (object != null ? object.getClass().getName() : "null") + ')'); } return object; }
Example 3
Source File: ZWaveScene.java From arcusplatform with Apache License 2.0 | 6 votes |
public static int calculatePriority(ProtocolMessage msg) { try { Protocol.Command cmdMsg = Protocol.Command.serde().fromBytes(ByteOrder.BIG_ENDIAN, msg.getValue(ZWaveExternalProtocol.INSTANCE).getPayload()); byte cmdClassId = (byte)( ((byte)cmdMsg.getCommandClassId()) & 0xFF ); byte cmdId = (byte)( ((byte)cmdMsg.getCommandId()) & 0xFF ); ConcurrentMap<Byte,Integer> cmdPriorities = priorities.computeIfAbsent(cmdClassId, (cid) -> new ConcurrentHashMap<>()); return cmdPriorities.computeIfAbsent(cmdId, (cmd) -> { String commandName = ZWaveAllCommandClasses.getClass(cmdClassId).get(cmdId).commandName; return (commandName.contains("set") && !commandName.contains("setup")) ? 1 //if the command changes a device state, return a higher priority : 0; }); } catch (Exception e){ log.warn("entering scene: error in decoding zwave message to assess priority, err:", e); } return 0; }
Example 4
Source File: DefaultNodeDeserializers.java From smithy with Apache License 2.0 | 5 votes |
private static ObjectCreatorFactory cachedCreator(ObjectCreatorFactory delegate) { ConcurrentMap<Pair<NodeType, Class>, NodeMapper.ObjectCreator> cache = new ConcurrentHashMap<>(); return (nodeType, target) -> { return cache.computeIfAbsent(Pair.of(nodeType, target), pair -> { return delegate.getCreator(pair.left, pair.right); }); }; }
Example 5
Source File: ConsumeQueueManager.java From qmq with Apache License 2.0 | 5 votes |
public ConsumeQueue getOrCreate(final String subject, final String group) { ConcurrentMap<String, ConsumeQueue> consumeQueues = queues.computeIfAbsent(subject, s -> new ConcurrentHashMap<>()); return consumeQueues.computeIfAbsent(group, g -> { Optional<Long> lastMaxSequence = getLastMaxSequence(subject, g); if (lastMaxSequence.isPresent()) { return new ConsumeQueue(storage, subject, g, lastMaxSequence.get() + 1); } else { OffsetBound consumerLogBound = storage.getSubjectConsumerLogBound(subject); long maxSequence = consumerLogBound == null ? 0 : consumerLogBound.getMaxOffset(); LOGGER.info("发现新的group:{} 订阅了subject: {},从最新的消息开始消费, 最新的sequence为:{}!", g, subject, maxSequence); return new ConsumeQueue(storage, subject, g, maxSequence); } }); }
Example 6
Source File: Customizer.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
/** * Create a wrapped customizer that guarantees that the {@link #customize(Object)} * method of the delegated <code>customizer</code> is called at most once per target. * @param customizer a customizer to be delegated * @param keyMapper a mapping function to produce the identifier of the target * @param <T> the type of the target to customize * @param <K> the type of the identifier of the target * @return a wrapped customizer */ static <T, K> Customizer<T> once(Customizer<T> customizer, Function<? super T, ? extends K> keyMapper) { final ConcurrentMap<K, Boolean> customized = new ConcurrentHashMap<>(); return t -> { final K key = keyMapper.apply(t); customized.computeIfAbsent(key, k -> { customizer.customize(t); return true; }); }; }
Example 7
Source File: RedisUserTokenManagerTests.java From hsweb-framework with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws InterruptedException { RedissonClient client = Redisson.create(); try { ConcurrentMap<String, SimpleUserToken> repo = client.getMap("hsweb.user-token", new SerializationCodec()); ConcurrentMap<String, Set<String>> userRepo = client.getMap("hsweb.user-token-u", new SerializationCodec()); userTokenManager = new DefaultUserTokenManager(repo, userRepo) { @Override protected Set<String> getUserToken(String userId) { userRepo.computeIfAbsent(userId,u->new HashSet<>()); return client.getSet("hsweb.user-token-"+userId, new SerializationCodec()); } }; userTokenManager.setAllopatricLoginMode(AllopatricLoginMode.deny); // userTokenManager=new DefaultUserTokenManager(); // userRepo.clear(); // repo.clear(); // for (int i = 0; i < 1000; i++) { // userTokenManager.signIn(IDGenerator.MD5.generate(), "sessionId", "admin", 60*3600*1000); // } // userTokenManager.signIn(IDGenerator.MD5.generate(), "sessionId", "admin2", 60*3600*1000); testGet(); testGetAll(); testSignOut(); testGetAll(); } finally { client.shutdown(); } }
Example 8
Source File: Scheduler.java From styx with Apache License 2.0 | 5 votes |
private boolean limitReached(final String resourceId, ConcurrentMap<String, Boolean> resourceExhaustedCache) { return resourceExhaustedCache.computeIfAbsent(resourceId, k -> { try { return !shardedCounter.counterHasSpareCapacity(resourceId); } catch (RuntimeException | IOException e) { log.warn("Failed to check resource counter limit", e); return false; } }); }
Example 9
Source File: AbstractHubDriver.java From arcusplatform with Apache License 2.0 | 5 votes |
protected static <T> Variable<T> mkvar(String driver, Version version, String name, Class<T> type, T def, boolean attr) { Variable<T> var = new Variable<T>(type, name, def, attr); ConcurrentMap<Version,Map<String,Class<?>>> dconvs = conversions.computeIfAbsent(driver, (k) -> new ConcurrentHashMap<>()); Map<String,Class<?>> convs = dconvs.computeIfAbsent(version, (v) -> new ConcurrentHashMap<>()); convs.put(var.key, type); return var; }
Example 10
Source File: ComputeBenchmark.java From caffeine with Apache License 2.0 | 4 votes |
private void setupConcurrentHashMap() { ConcurrentMap<Integer, Boolean> map = new ConcurrentHashMap<>(); benchmarkFunction = key -> map.computeIfAbsent(key, mappingFunction); }
Example 11
Source File: ConcurrentHashMap8Test.java From caffeine with Apache License 2.0 | 4 votes |
/** * computeIfAbsent adds when the given key is not present */ public void testComputeIfAbsent() { ConcurrentMap map = map5(); map.computeIfAbsent(six, (x) -> "Z"); assertTrue(map.containsKey(six)); }
Example 12
Source File: TopologyService.java From terracotta-platform with Apache License 2.0 | 4 votes |
private ExecutionChain<ServerEntity> whenServerEntity(long consumerId, String serverName) { ConcurrentMap<Long, ExecutionChain<ServerEntity>> entities = serverEntities.computeIfAbsent(serverName, name -> new ConcurrentHashMap<>()); return entities.computeIfAbsent(consumerId, key -> new ExecutionChain<>()); }
Example 13
Source File: TopologyService.java From terracotta-platform with Apache License 2.0 | 4 votes |
private ExecutionChain<Client> whenFetchClient(long consumerId, ClientDescriptor clientDescriptor) { ConcurrentMap<ClientDescriptor, ExecutionChain<Client>> fetches = entityFetches.computeIfAbsent(consumerId, cid -> new ConcurrentHashMap<>()); return fetches.computeIfAbsent(clientDescriptor, key -> new ExecutionChain<>()); }
Example 14
Source File: ConcurrentHashMap8Test.java From caffeine with Apache License 2.0 | 4 votes |
/** * computeIfAbsent does not add if function returns null */ public void testComputeIfAbsent3() { ConcurrentMap map = map5(); map.computeIfAbsent(six, (x) -> null); assertFalse(map.containsKey(six)); }
Example 15
Source File: CopierFactory.java From Copiers with Apache License 2.0 | 4 votes |
public static <F, T> CglibCopier<F, T> getOrCreateCglibCopier(Class<F> sourceClass, Class<T> targetClass, Converter converter) { ConcurrentMap<MapperKey<F, T>, CglibCopier<F, T>> cglibCache = CopierCache.<F, T>getInstance().getCglibCache(); MapperKey<F, T> mapperKey = new MapperKey<>(CGLIB, sourceClass, targetClass, converter); return cglibCache.computeIfAbsent(mapperKey, key -> new CglibCopier<>(key.getSourceClass(), key.getTargetClass(), converter)); }
Example 16
Source File: CopierFactory.java From Copiers with Apache License 2.0 | 4 votes |
public static <F, T> CglibCopier<F, T> getOrCreateCglibCopier(Class<F> sourceClass, Class<T> targetClass) { ConcurrentMap<MapperKey<F, T>, CglibCopier<F, T>> cglibCache = CopierCache.<F, T>getInstance().getCglibCache(); MapperKey<F, T> mapperKey = new MapperKey<>(CGLIB, sourceClass, targetClass); return cglibCache.computeIfAbsent(mapperKey, key -> new CglibCopier<>(key.getSourceClass(), key.getTargetClass())); }
Example 17
Source File: CopierFactory.java From Copiers with Apache License 2.0 | 4 votes |
public static <F, T> OrikaCopier<F, T> getOrCreateOrikaCopier(Class<F> sourceClass, Class<T> targetClass) { ConcurrentMap<MapperKey<F, T>, OrikaCopier<F, T>> orikaCache = CopierCache.<F, T>getInstance().getOrikaCache(); MapperKey<F, T> mapperKey = new MapperKey<>(ORIKA, sourceClass, targetClass); return orikaCache.computeIfAbsent(mapperKey, key -> new OrikaCopier.Builder<>(key.getSourceClass(), key.getTargetClass()).register()); }
Example 18
Source File: Scheduler.java From styx with Apache License 2.0 | 4 votes |
private void processInstance(StyxConfig config, Map<String, Resource> resources, ConcurrentMap<WorkflowId, Optional<Workflow>> workflows, WorkflowInstance instance, ConcurrentMap<String, Boolean> resourceExhaustedCache, AtomicLongMap<String> currentResourceUsage, AtomicLongMap<String> currentResourceDemand) { log.debug("Processing instance: {}", instance); // Get the run state or exit if it does not exist var runStateOpt = stateManager.getActiveState(instance); if (runStateOpt.isEmpty()) { return; } var runState = runStateOpt.orElseThrow(); // Look up the resources that are used by this workflow // Account current resource usage if (StateUtil.isConsumingResources(runState.state())) { runState.data().resourceIds().ifPresent(ids -> ids.forEach(currentResourceUsage::incrementAndGet)); } // Exit if this instance is not eligible for dequeue if (!shouldExecute(runState)) { return; } log.debug("Evaluating instance for dequeue: {}", instance); if (!config.globalEnabled()) { LOG.debug("Scheduling disabled, sending instance back to queue: {}", instance); stateManager.receiveIgnoreClosed(Event.retryAfter(instance, randomizedDelay()), runState.counter()); return; } // Get the workflow configuration var workflowOpt = workflows.computeIfAbsent(instance.workflowId(), this::readWorkflow); var workflowConfig = workflowOpt .map(Workflow::configuration) // Dummy placeholder .orElse(WorkflowConfiguration .builder() .id(instance.workflowId().id()) .schedule(Schedule.parse("")) .build()); var workflowResourceRefs = workflowResources(config.globalConcurrency().isPresent(), workflowOpt); var instanceResourceRefs = resourceDecorator.decorateResources( runState, workflowConfig, workflowResourceRefs); var unknownResources = instanceResourceRefs.stream() .filter(resourceRef -> !resources.containsKey(resourceRef)) .collect(toSet()); if (!unknownResources.isEmpty()) { var error = Event.runError(instance, "Referenced resources not found: " + unknownResources); stateManager.receiveIgnoreClosed(error, runState.counter()); return; } // Account resource demand by instances that are queued instanceResourceRefs.forEach(currentResourceDemand::incrementAndGet); // Check resource limits. This is racy and can give false positives but the transactional // checking happens later. This is just intended to avoid spinning on exhausted resources. final List<String> depletedResources = instanceResourceRefs.stream() .filter(resourceId -> limitReached(resourceId, resourceExhaustedCache)) .sorted() .collect(toList()); if (!depletedResources.isEmpty()) { log.debug("Resource limit reached for instance, not dequeueing: {}: exhausted resources={}", instance, depletedResources); MessageUtil.emitResourceLimitReachedMessage(stateManager, runState, depletedResources); return; } // Racy: some resources may have been removed (become unknown) by now; in that case the // counters code during dequeue will treat them as unlimited... sendDequeue(instance, runState, instanceResourceRefs); }
Example 19
Source File: ExtensionAdderProviders.java From powsybl-core with Mozilla Public License 2.0 | 4 votes |
static <O, E extends Extension<O>, B extends ExtensionAdder<O, E>> ExtensionAdderProvider findCachedProvider( String name, Class<B> type, ConcurrentMap<String, List<ExtensionAdderProvider>> providersMap, ConcurrentMap<Pair<String, Class>, ExtensionAdderProvider> cache) { return cache.computeIfAbsent(Pair.of(name, type), k -> findProvider(name, type, providersMap)); }
Example 20
Source File: StepParser.java From camel-k-runtime with Apache License 2.0 | 4 votes |
static Resolver caching(Resolver delegate) { final ConcurrentMap<String, StepParser> cache = new ConcurrentHashMap<>(); return (camelContext, stepId) -> cache.computeIfAbsent(stepId, key -> delegate.resolve(camelContext, key)); }