Example usage for java.util.concurrent ConcurrentMap get

List of usage examples for java.util.concurrent ConcurrentMap get

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.application.utils.FastDateParser.java

/**
 * Construct a Strategy that parses a Text field
 *
 * @param field            The Calendar field
 * @param definingCalendar The calendar to obtain the short and long values
 * @return a TextStrategy for the field and Locale
 *//*from   www  .java  2 s.co m*/
private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) {
    final ConcurrentMap<Locale, Strategy> cache = getCache(field);
    Strategy strategy = cache.get(locale);
    if (strategy == null) {
        strategy = field == Calendar.ZONE_OFFSET ? new TimeZoneStrategy(locale)
                : new TextStrategy(field, definingCalendar, locale);
        final Strategy inCache = cache.putIfAbsent(locale, strategy);
        if (inCache != null) {
            return inCache;
        }
    }
    return strategy;
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void setRangeEnd(String table, RangeRequest range, byte[] maxRow) {
    Validate.notNull(maxRow);/*from  w w  w  . j  a v a  2  s . co m*/
    ConcurrentMap<RangeRequest, byte[]> rangeEnds = rangeEndByTable.get(table);
    if (rangeEnds == null) {
        ConcurrentMap<RangeRequest, byte[]> newMap = Maps.newConcurrentMap();
        rangeEndByTable.putIfAbsent(table, newMap);
        rangeEnds = rangeEndByTable.get(table);
    }

    if (maxRow.length == 0) {
        rangeEnds.put(range, maxRow);
    }

    while (true) {
        byte[] curVal = rangeEnds.get(range);
        if (curVal == null) {
            byte[] oldVal = rangeEnds.putIfAbsent(range, maxRow);
            if (oldVal == null) {
                return;
            } else {
                continue;
            }
        }
        if (curVal.length == 0) {
            return;
        }
        if (UnsignedBytes.lexicographicalComparator().compare(curVal, maxRow) >= 0) {
            return;
        }
        if (rangeEnds.replace(range, curVal, maxRow)) {
            return;
        }
    }
}

From source file:org.apache.nifi.controller.scheduling.TestStandardProcessScheduler.java

@Before
public void setup() throws InitializationException {
    this.nifiProperties = NiFiProperties.createBasicNiFiProperties(propsFile, null);

    // load the system bundle
    systemBundle = SystemBundle.create(nifiProperties);
    ExtensionManager.discoverExtensions(systemBundle, Collections.emptySet());

    scheduler = new StandardProcessScheduler(Mockito.mock(ControllerServiceProvider.class), null,
            stateMgrProvider, nifiProperties);
    scheduler.setSchedulingAgent(SchedulingStrategy.TIMER_DRIVEN, Mockito.mock(SchedulingAgent.class));

    reportingTask = new TestReportingTask();
    final ReportingInitializationContext config = new StandardReportingInitializationContext(
            UUID.randomUUID().toString(), "Test", SchedulingStrategy.TIMER_DRIVEN, "5 secs",
            Mockito.mock(ComponentLog.class), null, nifiProperties, null);
    reportingTask.initialize(config);// w w w. j  a va 2s .  c o  m

    final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(null,
            variableRegistry);
    final ComponentLog logger = Mockito.mock(ComponentLog.class);
    final ReloadComponent reloadComponent = Mockito.mock(ReloadComponent.class);
    final LoggableComponent<ReportingTask> loggableComponent = new LoggableComponent<>(reportingTask,
            systemBundle.getBundleDetails().getCoordinate(), logger);
    taskNode = new StandardReportingTaskNode(loggableComponent, UUID.randomUUID().toString(), null, scheduler,
            validationContextFactory, new StandardComponentVariableRegistry(variableRegistry), reloadComponent);

    controller = Mockito.mock(FlowController.class);

    final ConcurrentMap<String, ProcessorNode> processorMap = new ConcurrentHashMap<>();
    Mockito.doAnswer(new Answer<ProcessorNode>() {
        @Override
        public ProcessorNode answer(InvocationOnMock invocation) throws Throwable {
            final String id = invocation.getArgumentAt(0, String.class);
            return processorMap.get(id);
        }
    }).when(controller).getProcessorNode(Mockito.anyString());

    Mockito.doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final ProcessorNode procNode = invocation.getArgumentAt(0, ProcessorNode.class);
            processorMap.putIfAbsent(procNode.getIdentifier(), procNode);
            return null;
        }
    }).when(controller).onProcessorAdded(Mockito.any(ProcessorNode.class));

    rootGroup = new MockProcessGroup(controller);
    Mockito.when(controller.getGroup(Mockito.anyString())).thenReturn(rootGroup);
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDateParser.java

/**
 * Construct a Strategy that parses a Text field
 * @param field The Calendar field/*from  w w  w .  jav  a 2s.c o m*/
 * @param definingCalendar The calendar to obtain the short and long values
 * @return a TextStrategy for the field and Locale
 */
private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) {
    final ConcurrentMap<Locale, Strategy> cache = getCache(field);
    Strategy strategy = cache.get(locale);
    if (strategy == null) {
        strategy = field == Calendar.ZONE_OFFSET ? new TimeZoneStrategy(locale)
                : new CaseInsensitiveTextStrategy(field, definingCalendar, locale);
        final Strategy inCache = cache.putIfAbsent(locale, strategy);
        if (inCache != null) {
            return inCache;
        }
    }
    return strategy;
}

From source file:se.idsecurity.ldifcompare.LdifCompare.java

/**
 * Compare LDIF entries using DN, if the DN is the same in both entries then the entries should be compared
 * @param source Entries from the "left" file
 * @param target Entries from the "right" file
 * @param diffFile Write results to this file
 * @param comment Comment to write to the file
 * @throws FileNotFoundException /*from  ww w  .j a v  a2s.  co  m*/
 * @since 1.2
 */
private void getDiffUsingDN(Set<Entry> source, Set<Entry> target, File diffFile, String comment)
        throws FileNotFoundException {
    StopWatch sw = new StopWatch();
    sw.start();

    ConcurrentMap<String, Entry> collect = source.parallelStream()
            .collect(Collectors.toConcurrentMap(Entry::getDN, Function.identity()));
    sw.stop();
    logger.error("Set -> ConcurrentMap: " + sw.toString());
    sw.reset();

    try (PrintWriter writer = new PrintWriter(diffFile)) {

        writer.println(comment);

        sw.start();
        for (Entry targetEntry : target) {
            String dn = targetEntry.getDN();
            Entry sEntry = collect.get(dn);
            if (sEntry != null) {
                writer.println();
                writer.println(dn);
                List<Modification> diff = Entry.diff(sEntry, targetEntry, false);
                for (Modification mod : diff) {
                    writer.println(mod);
                }
            }

        }
    }
    sw.stop();
    logger.error("Time taken to loop inside getDiffUsingDN: " + sw.toString());

}

From source file:com.alibaba.jstorm.daemon.nimbus.TopologyMetricsRunnable.java

public Map<String, Long> registerMetrics(String topologyId, Set<String> metricNames) {
    TimeTicker ticker = new TimeTicker(TimeUnit.MILLISECONDS, true);

    ConcurrentMap<String, Long> memMeta = topologyMetricContexts.get(topologyId).getMemMeta();
    Map<String, Long> ret = new HashMap<>();
    for (String metricName : metricNames) {
        Long id = memMeta.get(metricName);
        if (id != null && MetricUtils.isValidId(id)) {
            ret.put(metricName, id);/*from w  ww .java  2s  . co m*/
        } else {
            id = metricIDGenerator.genMetricId(metricName);
            Long old = memMeta.putIfAbsent(metricName, id);
            if (old == null) {
                ret.put(metricName, id);
            } else {
                ret.put(metricName, old);
            }
        }
    }

    long cost = ticker.stop();
    LOG.info("register metrics, topology:{}, size:{}, cost:{}", topologyId, metricNames.size(), cost);

    return ret;
}

From source file:org.opendaylight.ovsdb.plugin.impl.ConfigurationServiceImpl.java

@Override
public Row<GenericTableSchema> getRow(Node node, String databaseName, String tableName, UUID uuid)
        throws OvsdbPluginException {
    ConcurrentMap<UUID, Row<GenericTableSchema>> rows = this.getRows(node, databaseName, tableName);
    if (rows != null) {
        return rows.get(uuid);
    }//w w w. j  a v a  2 s.co  m
    return null;
}

From source file:com.clustercontrol.monitor.run.factory.RunMonitor.java

/**
 * ?????????????/*from ww w.j a  v a 2s . c  om*/
 * ?????????Set?
 * 
 * ????Set??????Set?synchronized?????????
 * 
 * @param monitorType
 * @param facilityId
 * @return
 */
private static Set<Integer> getPlannedTasksForNodeAggregateMonitor(String monitorType, String facilityId) {
    // ?????????
    ConcurrentMap<String, Set<Integer>> node2task = plannedTaskForNodeAggregateMonitor.get(monitorType);
    if (node2task == null) {
        ConcurrentMap<String, Set<Integer>> newNode2task = new ConcurrentHashMap<>();
        node2task = plannedTaskForNodeAggregateMonitor.putIfAbsent(monitorType, newNode2task);
        if (node2task == null) {
            node2task = newNode2task;
        }
    }
    // ??????????????
    Set<Integer> tasks = node2task.get(facilityId);
    if (tasks == null) {
        Set<Integer> newTasks = new HashSet<>();
        tasks = node2task.putIfAbsent(facilityId, newTasks);
        if (tasks == null) {
            tasks = newTasks;
        }
    }
    return tasks;
}

From source file:org.onosproject.store.trivial.SimpleDeviceStore.java

@Override
public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
        Collection<PortStatistics> newStatsCollection) {

    ConcurrentMap<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
    ConcurrentMap<PortNumber, PortStatistics> newStatsMap = Maps.newConcurrentMap();
    ConcurrentMap<PortNumber, PortStatistics> deltaStatsMap = Maps.newConcurrentMap();

    if (prvStatsMap != null) {
        for (PortStatistics newStats : newStatsCollection) {
            PortNumber port = PortNumber.portNumber(newStats.port());
            PortStatistics prvStats = prvStatsMap.get(port);
            DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
            PortStatistics deltaStats = builder.build();
            if (prvStats != null) {
                deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
            }//w  ww. j a v a2 s.co  m
            deltaStatsMap.put(port, deltaStats);
            newStatsMap.put(port, newStats);
        }
    } else {
        for (PortStatistics newStats : newStatsCollection) {
            PortNumber port = PortNumber.portNumber(newStats.port());
            newStatsMap.put(port, newStats);
        }
    }
    devicePortDeltaStats.put(deviceId, deltaStatsMap);
    devicePortStats.put(deviceId, newStatsMap);
    return new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
}

From source file:com.cubeia.firebase.server.lobby.systemstate.StateLobby.java

public String printPacketCounts() {
    ConcurrentMap<LobbyPath, Integer> fullPacketCount = new ConcurrentHashMap<LobbyPath, Integer>();
    ConcurrentMap<LobbyPath, Integer> deltaPacketCount = new ConcurrentHashMap<LobbyPath, Integer>();

    for (SnapshotGenerator generator : generators.values()) {
        ConcurrentMap<LobbyPath, FullSnapshot> fullSnapshots = generator.getFullSnapshots();
        ConcurrentMap<LobbyPath, DeltaSnapshot> deltaSnapshots = generator.getDeltaSnapshots();

        for (LobbyPath path : fullSnapshots.keySet()) {
            FullSnapshot fullSnapshot = fullSnapshots.get(path);
            fullPacketCount.put(path, fullSnapshot.getLobbyData().size());
        }//from   www . j  av a 2  s.  co m

        for (LobbyPath path : deltaSnapshots.keySet()) {
            DeltaSnapshot deltaSnapshot = deltaSnapshots.get(path);
            deltaPacketCount.put(path, deltaSnapshot.getLobbyData().size());
        }
    }

    String info = "Lobby Snapshots Per Chached Lobby Path\n";
    info += "-----------------------\n";
    info += "Full Packet Path Count:  " + fullPacketCount.size() + "\n";
    info += "Delta Packet Path Count: " + deltaPacketCount.size() + "\n";
    info += "-----------------------\n";
    info += "FULL PACKET COUNT PER PATH\n";
    for (LobbyPath path : fullPacketCount.keySet()) {
        info += StringUtils.rightPad(path.toString(), 60) + "\t : " + fullPacketCount.get(path) + "\n";
    }
    info += "-----------------------\n";
    info += "DELTA PACKET COUNT PER PATH\n";
    for (LobbyPath path : deltaPacketCount.keySet()) {
        info += StringUtils.rightPad(path.toString(), 60) + "\t : " + deltaPacketCount.get(path) + "\n";
        ;
    }

    return info;
}