Example usage for com.google.common.collect Maps newConcurrentMap

List of usage examples for com.google.common.collect Maps newConcurrentMap

Introduction

In this page you can find the example usage for com.google.common.collect Maps newConcurrentMap.

Prototype

public static <K, V> ConcurrentMap<K, V> newConcurrentMap() 

Source Link

Document

Returns a general-purpose instance of ConcurrentMap , which supports all optional operations of the ConcurrentMap interface.

Usage

From source file:org.apache.bookkeeper.tests.integration.topologies.BKCluster.java

private BKCluster(BKClusterSpec spec) {
    this.spec = spec;
    this.clusterName = spec.clusterName();
    this.network = Network.newNetwork();
    this.metadataContainer = (MetadataStoreContainer) new ZKContainer(clusterName).withNetwork(network)
            .withNetworkAliases(ZKContainer.HOST_NAME);
    this.bookieContainers = Maps.newTreeMap();
    this.internalEndpointsToExternalEndpoints = Maps.newConcurrentMap();
    this.numBookies = spec.numBookies();
    this.extraServerComponents = spec.extraServerComponents();
    this.enableContainerLog = spec.enableContainerLog();
}

From source file:uk.ac.cam.cl.dtg.segue.api.monitors.InMemoryMisuseMonitor.java

@Override
public synchronized void notifyEvent(final String agentIdentifier, final String eventLabel,
        final Integer adjustmentValue) throws SegueResourceMisuseException {
    Validate.notBlank(agentIdentifier);// www.ja  v  a2s .c  o m
    Validate.notBlank(eventLabel);
    Validate.notNull(adjustmentValue);
    Validate.isTrue(adjustmentValue >= 0, "Expected positive integer value.");

    IMisuseHandler handler = handlerMap.get(eventLabel);
    Validate.notNull(handler, "No handler has been registered for " + eventLabel);

    Map<String, Entry<Date, Integer>> existingHistory = nonPersistentDatabase.getIfPresent(agentIdentifier);

    if (null == existingHistory) {
        existingHistory = Maps.newConcurrentMap();

        existingHistory.put(eventLabel, immutableEntry(new Date(), adjustmentValue));
        nonPersistentDatabase.put(agentIdentifier, existingHistory);
    } else {
        Entry<Date, Integer> entry = existingHistory.get(eventLabel);
        if (null == entry) {
            existingHistory.put(eventLabel, immutableEntry(new Date(), adjustmentValue));
            log.debug("New Event " + existingHistory.get(eventLabel));
        } else {

            // deal with expired events
            if (!isCountStillFresh(entry.getKey(), handler.getAccountingIntervalInSeconds())) {
                existingHistory.put(eventLabel, immutableEntry(new Date(), adjustmentValue));
                log.debug("Event expired starting count over");
            } else {
                // last events not expired yet so add them.
                existingHistory.put(eventLabel,
                        immutableEntry(entry.getKey(), entry.getValue() + adjustmentValue));
                log.debug("Event NOT expired so adding one " + existingHistory.get(eventLabel));
            }

            entry = existingHistory.get(eventLabel);
            int previousValue = entry.getValue() - adjustmentValue;

            // deal with threshold violations
            if (handler.getSoftThreshold() != null && (previousValue < handler.getSoftThreshold()
                    && entry.getValue() >= handler.getSoftThreshold())) {
                handler.executeSoftThresholdAction(
                        String.format("(%s) has exceeded the soft limit!", agentIdentifier));
            }

            if (handler.getHardThreshold() != null && (previousValue < handler.getHardThreshold()
                    && entry.getValue() >= handler.getHardThreshold())) {
                String errMessage = String.format("(%s) has exceeded the hard limit!", agentIdentifier);

                handler.executeHardThresholdAction(errMessage);
            }

            if (handler.getHardThreshold() != null && entry.getValue() > handler.getHardThreshold()) {
                throw new SegueResourceMisuseException("Exceeded resource usage limit on " + eventLabel);
            }
        }
    }
}

From source file:com.griddynamics.jagger.diagnostics.thread.sampling.SamplingProfilerImpl.java

@Override
public void startPolling() throws InterruptedException {
    if (isRunning.compareAndSet(false, true)) {

        log.debug("SamplingProfiler {} : Starting profiling", identifier);

        runtimeGraphs = Maps.newConcurrentMap();

        pollingThread = new PollingThread();
        pollingThread.start();//from ww w  . ja  va  2  s. c o  m
    } else {
        log.error("Polling is already started!!!! Polling will be stopped, cleaned and restarted!");
        stopPolling();
        pollingThread.join();
        isRunning.set(false);
        startPolling();
    }
}

From source file:org.glowroot.agent.plugin.servlet.ResponseHeaderComponent.java

synchronized void setHeader(String name, Object value) {
    if (responseHeaders == null) {
        responseHeaders = Maps.newConcurrentMap();
    }//from   w  ww .  ja va 2  s .co  m
    String nameUpper = name.toUpperCase(Locale.ENGLISH);
    ResponseHeader responseHeader = responseHeaders.get(nameUpper);
    if (responseHeader == null) {
        responseHeaders.put(nameUpper, new ResponseHeader(name, value));
    } else {
        responseHeader.setValue(value);
    }
}

From source file:org.apache.spark.network.shuffle.ExternalShuffleBlockManager.java

@VisibleForTesting
ExternalShuffleBlockManager(TransportConf conf, Executor directoryCleaner) {
    this.conf = conf;
    this.executors = Maps.newConcurrentMap();
    this.directoryCleaner = directoryCleaner;
}

From source file:com.google.gitiles.FakeHttpServletRequest.java

private FakeHttpServletRequest(String hostName, int port, String contextPath, String servletPath, String path) {
    this.hostName = checkNotNull(hostName, "hostName");
    checkArgument(port > 0);// w  w w .  j  a v a 2 s . c  o m
    this.port = port;
    this.contextPath = checkNotNull(contextPath, "contextPath");
    this.servletPath = checkNotNull(servletPath, "servletPath");
    attributes = Maps.newConcurrentMap();
    parameters = LinkedListMultimap.create();
    headers = LinkedListMultimap.create();
}

From source file:co.cask.cdap.hive.serde.ObjectSerializer.java

public Writable serialize(Object o, ObjectInspector objectInspector) {
    //overwrite field names (as they get lost by Hive)
    StructTypeInfo structTypeInfo = (StructTypeInfo) TypeInfoUtils
            .getTypeInfoFromObjectInspector(objectInspector);
    structTypeInfo.setAllStructFieldNames(columnNames);

    List<TypeInfo> info = structTypeInfo.getAllStructFieldTypeInfos();
    List<String> names = structTypeInfo.getAllStructFieldNames();

    Map<String, Object> recordMap = Maps.newConcurrentMap();
    List<Object> recordObjects = ((StructObjectInspector) objectInspector).getStructFieldsDataAsList(o);

    for (int structIndex = 0; structIndex < info.size(); structIndex++) {
        Object obj = recordObjects.get(structIndex);
        TypeInfo objType = info.get(structIndex);
        if (obj instanceof LazyNonPrimitive || obj instanceof LazyPrimitive) {
            // In case the SerDe that deserialized the object is the one of a native table
            recordMap.put(names.get(structIndex), fromLazyObject(objType, obj));
        } else if (obj instanceof Writable) {
            // Native tables sometimes introduce primitive Writable objects at this point
            recordMap.put(names.get(structIndex), fromWritable((Writable) obj));
        } else {//from ww  w . j  a v a  2 s. c  o m
            // In case the deserializer is the DatasetSerDe
            recordMap.put(names.get(structIndex), serialize(obj, objType));
        }
    }

    // TODO Improve serialization logic - CDAP-11
    return new Text(GSON.toJson(recordMap));
}

From source file:org.thiesen.jiffs.jobs.clusterer.Clusterer.java

private Map<String, Long> findClusters() {
    final Iterable<StoryDBO> unprocessed = _storyDAO.findForClustering();
    final StopWatch watch = new StopWatch();

    watch.start();// w  w  w.  j a v  a 2s  .  c  o m

    final Map<String, Long> foundClusters = Maps.newConcurrentMap();
    final Semaphore maxEnqueedTasks = new Semaphore(100000);
    final List<ClusterItem> clusterItems = Lists.newLinkedList(transform(unprocessed));
    final Iterator<ClusterItem> firstIterator = clusterItems.iterator();
    while (firstIterator.hasNext()) {
        final ClusterItem firstItem = firstIterator.next();
        for (final ClusterItem secondItem : clusterItems) {
            if (firstItem == secondItem) {
                continue;
            }
            EXECUTOR.submit(new ClusterFinder(maxEnqueedTasks, foundClusters, firstItem, secondItem));
            maxEnqueedTasks.acquireUninterruptibly();
        }
        firstIterator.remove();
    }

    EXECUTOR.shutdown();

    try {
        EXECUTOR.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        Thread.interrupted();
    }
    watch.stop();

    System.out.println("Clustering took " + watch);

    return foundClusters;
}

From source file:org.ros.concurrent.RetryingExecutorService.java

/**
 * @param scheduledExecutorService/*from  ww w.  jav  a  2 s .co m*/
 *          the {@link ExecutorService} to wrap
 */
public RetryingExecutorService(ScheduledExecutorService scheduledExecutorService) {
    this.scheduledExecutorService = scheduledExecutorService;
    retryLoop = new RetryLoop();
    latches = Maps.newConcurrentMap();
    callables = Maps.newConcurrentMap();
    completionService = new ExecutorCompletionService<Boolean>(scheduledExecutorService);
    mutex = new Object();
    retryDelay = DEFAULT_RETRY_DELAY;
    retryTimeUnit = DEFAULT_RETRY_TIME_UNIT;
    running = true;
    // TODO(damonkohler): Unify this with the passed in ExecutorService.
    scheduledExecutorService.execute(retryLoop);
}

From source file:com.google.gerrit.util.http.testutil.FakeHttpServletRequest.java

public FakeHttpServletRequest(String hostName, int port, String contextPath, String servletPath) {
    this.hostName = checkNotNull(hostName, "hostName");
    checkArgument(port > 0);// w w w .j a va2 s  . c  o m
    this.port = port;
    this.contextPath = checkNotNull(contextPath, "contextPath");
    this.servletPath = checkNotNull(servletPath, "servletPath");
    attributes = Maps.newConcurrentMap();
    parameters = LinkedListMultimap.create();
    headers = LinkedListMultimap.create();
}