Example usage for java.util.concurrent ConcurrentMap putIfAbsent

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

Introduction

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

Prototype

V putIfAbsent(K key, V value);

Source Link

Document

If the specified key is not already associated with a value, associates it with the given value.

Usage

From source file:com.sworddance.beans.BeanWorker.java

/**
 * @param clazz/*www  . ja va 2  s  .c  o m*/
 * @param propMap
 * @param propertyName
 * @param readOnly if true and if propertyMethodChain has not been found then only the get method is searched for.
 * @return the propertyMethodChain
 * @throws ApplicationIllegalArgumentException if the propertyName is not actually a property.
 */
protected PropertyMethodChain addPropertyMethodChainIfAbsent(Class<?> clazz,
        ConcurrentMap<String, PropertyMethodChain> propMap, String propertyName, boolean readOnly)
        throws ApplicationIllegalArgumentException {
    if (!propMap.containsKey(propertyName)) {
        List<PropertyMethodChain> propertyMethodChains = newPropertyMethodChain(clazz, propertyName, readOnly,
                allowIntermediateProperties);
        ApplicationIllegalArgumentException.valid(isNotEmpty(propertyMethodChains), clazz,
                " has no property named '", propertyName, "'");
        for (PropertyMethodChain propertyMethodChain : propertyMethodChains) {
            propMap.putIfAbsent(propertyMethodChain.getProperty(), propertyMethodChain);
        }
    } else {
        // TODO: check to see if readOnly is false
    }
    return propMap.get(propertyName);
}

From source file:com.alibaba.jstorm.daemon.nimbus.metric.ClusterMetricsContext.java

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

    TopologyMetricContext topologyMetricContext = topologyMetricContexts.get(topologyId);
    if (topologyMetricContext == null) {
        LOG.warn("topology metrics context does not exist for topology:{}!!!", topologyId);
        return new HashMap<>();
    }/*from ww  w  .  j  a  v a 2 s . c  o m*/

    //        if (!topologyMetricContext.finishSyncRemote()) {
    //            LOG.warn("waiting for topology {} to finish sync with remote.", topologyId);
    //            return new HashMap<>();
    //        }

    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);
        } 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:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void setRangeEnd(String table, RangeRequest range, byte[] maxRow) {
    Validate.notNull(maxRow);//w  ww . j  a v  a  2 s .  c  o  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.sling.models.impl.AdapterImplementations.java

public void registerModelToResourceType(final Bundle bundle, final String resourceType,
        final Class<?> adaptableType, final Class<?> clazz) {
    if (resourceType.startsWith("/")) {
        log.warn("Registering model class {} for adaptable {} with absolute resourceType {}.",
                new Object[] { clazz, adaptableType, resourceType });
    }//from  w  w  w. ja v  a 2s. c o m
    ConcurrentMap<String, Class<?>> map;
    ConcurrentMap<Bundle, List<String>> resourceTypeRemovalLists;
    if (adaptableType == Resource.class) {
        map = resourceTypeMappingsForResources;
        resourceTypeRemovalLists = resourceTypeRemovalListsForResources;
    } else if (adaptableType == SlingHttpServletRequest.class) {
        map = resourceTypeMappingsForRequests;
        resourceTypeRemovalLists = resourceTypeRemovalListsForRequests;
    } else {
        log.warn(
                "Found model class {} with resource type {} for adaptable {}. Unsupported type for resourceType binding.",
                new Object[] { clazz, resourceType, adaptableType });
        return;
    }
    Class<?> existingMapping = map.putIfAbsent(resourceType, clazz);
    if (existingMapping == null) {
        resourceTypeRemovalLists.putIfAbsent(bundle, new CopyOnWriteArrayList<String>());
        resourceTypeRemovalLists.get(bundle).add(resourceType);
    } else {
        log.warn(
                "Skipped registering {} for resourceType {} under adaptable {} because of existing mapping to {}",
                new Object[] { clazz, resourceType, adaptableType, existingMapping });
    }
}

From source file:org.mule.module.logging.MuleLogFactory.java

public Log getInstance(String name) throws LogConfigurationException {
    final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    ConcurrentMap<String, Log> loggerMap = repository.get(ccl == null ? NO_CCL_CLASSLOADER : ccl.hashCode());

    if (loggerMap == null) {
        loggerMap = new ConcurrentHashMap<String, Log>();

        final ConcurrentMap<String, Log> previous = repository
                .putIfAbsent(ccl == null ? NO_CCL_CLASSLOADER : ccl.hashCode(), loggerMap);
        if (previous != null) {
            loggerMap = previous;//w w  w . ja  va 2  s.c om
        }

        if (ccl != null) {
            // must save a strong ref to the PhantomReference in order for it to stay alive and work
            refs.put(new PhantomReference<ClassLoader>(ccl, referenceQueue), ccl.hashCode());
        }

    }

    Log instance = loggerMap.get(name);

    if (instance == null) {
        Logger logger = LoggerFactory.getLogger(name);
        if (logger instanceof LocationAwareLogger) {
            instance = new MuleLocationAwareLog((LocationAwareLogger) logger);
        } else {
            instance = new MuleLog(logger);
        }
        final Log previous = loggerMap.putIfAbsent(name, instance);
        if (previous != null) {
            // someone got there before us
            instance = previous;
        }
    }

    return instance;
}

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 ww w  .j ava 2s .c om
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.clustercontrol.monitor.run.factory.RunMonitor.java

/**
 * ?????????????/* w  w  w. j a  va 2s.  c o m*/
 * ?????????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.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  .  j a v a2s .  c om
 * @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:org.jasig.portal.portlets.search.SearchPortletController.java

/**
 * Performs a search of the explicitly configured {@link IPortalSearchService}s. This
 * is done as an event handler so that it can run concurrently with the other portlets
 * handling the search request//  w w  w  .  j a  v  a 2s .  com
 */
@EventMapping(SearchConstants.SEARCH_REQUEST_QNAME_STRING)
public void handleSearchRequest(EventRequest request, EventResponse response) {
    final Event event = request.getEvent();
    final SearchRequest searchQuery = (SearchRequest) event.getValue();

    //Map used to track searches that have been handled, used so that one search doesn't get duplicate results
    ConcurrentMap<String, Boolean> searchHandledCache;
    final PortletSession session = request.getPortletSession();
    synchronized (org.springframework.web.portlet.util.PortletUtils.getSessionMutex(session)) {
        searchHandledCache = (ConcurrentMap<String, Boolean>) session.getAttribute(SEARCH_HANDLED_CACHE_NAME,
                PortletSession.APPLICATION_SCOPE);
        if (searchHandledCache == null) {
            searchHandledCache = CacheBuilder.newBuilder().maximumSize(20)
                    .expireAfterAccess(5, TimeUnit.MINUTES).<String, Boolean>build().asMap();
            session.setAttribute(SEARCH_HANDLED_CACHE_NAME, searchHandledCache,
                    PortletSession.APPLICATION_SCOPE);
        }
    }

    final String queryId = searchQuery.getQueryId();
    if (searchHandledCache.putIfAbsent(queryId, Boolean.TRUE) != null) {
        //Already handled this search request
        return;
    }

    //Create the results
    final SearchResults results = new SearchResults();
    results.setQueryId(queryId);
    results.setWindowId(request.getWindowID());
    final List<SearchResult> searchResultList = results.getSearchResult();

    //Run the search for each service appending the results
    for (IPortalSearchService searchService : searchServices) {
        try {
            final SearchResults serviceResults = searchService.getSearchResults(request, searchQuery);
            searchResultList.addAll(serviceResults.getSearchResult());
        } catch (Exception e) {
            logger.warn(searchService.getClass() + " threw an exception when searching, it will be ignored. "
                    + searchQuery, e);
        }
    }

    //Respond with a results event if results were found
    if (!searchResultList.isEmpty()) {
        response.setEvent(SearchConstants.SEARCH_RESULTS_QNAME, results);
    }
}

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);//from www.j  a v  a2s . c  om

    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);
}