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.onosproject.store.primitives.impl.EventuallyConsistentMapImpl.java

/**
 * Creates a new eventually consistent map shared amongst multiple instances.
 * <p>//from   w  w  w  . ja  va 2s . c  o m
 * See {@link org.onosproject.store.service.EventuallyConsistentMapBuilder}
 * for more description of the parameters expected by the map.
 * </p>
 *
 * @param mapName               a String identifier for the map.
 * @param clusterService        the cluster service
 * @param clusterCommunicator   the cluster communications service
 * @param ns                    a Kryo namespace that can serialize
 *                              both K and V
 * @param timestampProvider     provider of timestamps for K and V
 * @param peerUpdateFunction    function that provides a set of nodes to immediately
 *                              update to when there writes to the map
 * @param eventExecutor         executor to use for processing incoming
 *                              events from peers
 * @param communicationExecutor executor to use for sending events to peers
 * @param backgroundExecutor    executor to use for background anti-entropy
 *                              tasks
 * @param tombstonesDisabled    true if this map should not maintain
 *                              tombstones
 * @param antiEntropyPeriod     period that the anti-entropy task should run
 * @param antiEntropyTimeUnit   time unit for anti-entropy period
 * @param convergeFaster        make anti-entropy try to converge faster
 * @param persistent            persist data to disk
 * @param persistenceService    persistence service
 */
EventuallyConsistentMapImpl(String mapName, ClusterService clusterService,
        ClusterCommunicationService clusterCommunicator, KryoNamespace ns,
        BiFunction<K, V, Timestamp> timestampProvider, BiFunction<K, V, Collection<NodeId>> peerUpdateFunction,
        ExecutorService eventExecutor, ExecutorService communicationExecutor,
        ScheduledExecutorService backgroundExecutor, boolean tombstonesDisabled, long antiEntropyPeriod,
        TimeUnit antiEntropyTimeUnit, boolean convergeFaster, boolean persistent,
        PersistenceService persistenceService) {
    this.mapName = mapName;
    this.serializer = createSerializer(ns);
    this.persistenceService = persistenceService;
    this.persistent = persistent;
    if (persistent) {
        items = this.persistenceService.<K, MapValue<V>>persistentMapBuilder()
                .withName(PERSISTENT_LOCAL_MAP_NAME).withSerializer(this.serializer).build();
    } else {
        items = Maps.newConcurrentMap();
    }
    senderPending = Maps.newConcurrentMap();
    destroyedMessage = mapName + ERROR_DESTROYED;

    this.clusterService = clusterService;
    this.clusterCommunicator = clusterCommunicator;
    this.localNodeId = clusterService.getLocalNode().id();

    this.timestampProvider = timestampProvider;

    if (peerUpdateFunction != null) {
        this.peerUpdateFunction = peerUpdateFunction;
    } else {
        this.peerUpdateFunction = (key, value) -> clusterService.getNodes().stream().map(ControllerNode::id)
                .filter(nodeId -> !nodeId.equals(localNodeId)).collect(Collectors.toList());
    }

    if (eventExecutor != null) {
        this.executor = eventExecutor;
    } else {
        // should be a normal executor; it's used for receiving messages
        this.executor = Executors.newFixedThreadPool(8, groupedThreads("onos/ecm", mapName + "-fg-%d", log));
    }

    if (communicationExecutor != null) {
        this.communicationExecutor = communicationExecutor;
    } else {
        // sending executor; should be capped
        //TODO this probably doesn't need to be bounded anymore
        this.communicationExecutor = newFixedThreadPool(8,
                groupedThreads("onos/ecm", mapName + "-publish-%d", log));
    }

    if (backgroundExecutor != null) {
        this.backgroundExecutor = backgroundExecutor;
    } else {
        this.backgroundExecutor = newSingleThreadScheduledExecutor(
                groupedThreads("onos/ecm", mapName + "-bg-%d", log));
    }

    // start anti-entropy thread
    this.backgroundExecutor.scheduleAtFixedRate(this::sendAdvertisement, initialDelaySec, antiEntropyPeriod,
            antiEntropyTimeUnit);

    updateMessageSubject = new MessageSubject("ecm-" + mapName + "-update");
    clusterCommunicator.addSubscriber(updateMessageSubject, serializer::decode, this::processUpdates,
            this.executor);

    antiEntropyAdvertisementSubject = new MessageSubject("ecm-" + mapName + "-anti-entropy");
    clusterCommunicator.addSubscriber(antiEntropyAdvertisementSubject, serializer::decode,
            this::handleAntiEntropyAdvertisement, serializer::encode, this.backgroundExecutor);

    updateRequestSubject = new MessageSubject("ecm-" + mapName + "-update-request");
    clusterCommunicator.addSubscriber(updateRequestSubject, serializer::decode, this::handleUpdateRequests,
            this.backgroundExecutor);

    if (!tombstonesDisabled) {
        previousTombstonePurgeTime = 0;
        this.backgroundExecutor.scheduleWithFixedDelay(this::purgeTombstones, initialDelaySec,
                antiEntropyPeriod, TimeUnit.SECONDS);
    }

    this.tombstonesDisabled = tombstonesDisabled;
    this.lightweightAntiEntropy = !convergeFaster;

    // Initiate first round of Gossip
    this.bootstrap();
}

From source file:com.google.sampling.experiential.server.EventServlet.java

private String jsonifyEvents(EventQueryResultPair eventQueryPair, boolean anon, String timezoneId,
        boolean includePhotos, Float protocolVersion) {
    ObjectMapper mapper = JsonConverter.getObjectMapper();

    try {//  w ww.j  a  v a  2 s . c  o m
        List<EventDAO> eventDAOs = Lists.newArrayList();
        for (Event event : eventQueryPair.getEvents()) {
            String userId = event.getWho();
            if (anon) {
                userId = Event.getAnonymousId(userId);
            }
            DateTime responseDateTime = event.getResponseTimeWithTimeZone(event.getTimeZone());
            DateTime scheduledDateTime = event.getScheduledTimeWithTimeZone(event.getTimeZone());
            final List<WhatDAO> whatMap = EventRetriever.convertToWhatDAOs(event.getWhat());
            List<PhotoBlob> photos = event.getBlobs();
            String[] photoBlobs = null;
            if (includePhotos && photos != null && photos.size() > 0) {

                photoBlobs = new String[photos.size()];

                Map<String, PhotoBlob> photoByNames = Maps.newConcurrentMap();
                for (PhotoBlob photoBlob : photos) {
                    photoByNames.put(photoBlob.getName(), photoBlob);
                }
                for (WhatDAO currentWhat : whatMap) {
                    String value = null;
                    if (photoByNames.containsKey(currentWhat.getName())) {
                        byte[] photoData = photoByNames.get(currentWhat.getName()).getValue();
                        if (photoData != null && photoData.length > 0) {
                            String photoString = new String(Base64.encodeBase64(photoData));
                            if (!photoString.equals("==")) {
                                value = photoString;
                            } else {
                                value = "";
                            }
                        } else {
                            value = "";
                        }
                        currentWhat.setValue(value);
                    }
                }
            }

            eventDAOs.add(new EventDAO(userId, new DateTime(event.getWhen()), event.getExperimentName(),
                    event.getLat(), event.getLon(), event.getAppId(), event.getPacoVersion(), whatMap,
                    event.isShared(), responseDateTime, scheduledDateTime, null,
                    Long.parseLong(event.getExperimentId()), event.getExperimentVersion(), event.getTimeZone(),
                    event.getExperimentGroupName(), event.getActionTriggerId(), event.getActionTriggerSpecId(),
                    event.getActionId()));
        }
        EventDAOQueryResultPair eventDaoQueryResultPair = new EventDAOQueryResultPair(eventDAOs,
                eventQueryPair.getCursor());
        String finalRes = null;
        log.info("protocol version: " + protocolVersion);
        if (protocolVersion != null && protocolVersion < 5) {
            finalRes = mapper.writerWithView(Views.V4.class).writeValueAsString(eventDaoQueryResultPair);
        } else {
            mapper.setDateFormat(new ISO8601DateFormat());
            finalRes = mapper.writerWithView(Views.V5.class).writeValueAsString(eventDaoQueryResultPair);
        }
        return finalRes;
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "Error could not retrieve events as json";
}

From source file:org.onosproject.incubator.store.virtual.impl.SimpleVirtualIntentStore.java

/**
 * Returns the current intent map for a specific virtual network.
 *
 * @param networkId a virtual network identifier
 * @return the current map for the requested virtual network
 *///w ww  .  j av  a  2  s.c  o m
private Map<Key, IntentData> getCurrentMap(NetworkId networkId) {
    currentByNetwork.computeIfAbsent(networkId, n -> Maps.newConcurrentMap());
    return currentByNetwork.get(networkId);
}

From source file:org.ow2.proactive.resourcemanager.nodesource.infrastructure.AzureInfrastructure.java

/**
 * Default constructor
 */
public AzureInfrastructure() {
    nodesPerInstances = Maps.newConcurrentMap();
}

From source file:org.netarchlab.AbstractUpgradableFabricApp.java

private void init() {

    // Reset any previous state
    synchronized (this) {
        flowRuleGenerated = Boolean.FALSE;
        leafSwitches = Sets.newHashSet();
        spineSwitches = Sets.newHashSet();
        deviceFlowRules = Maps.newConcurrentMap();
        ruleFlags = Maps.newConcurrentMap();
        contextFlags = Maps.newConcurrentMap();
    }//from   w  w w . ja v a 2  s  . c  om

    // Start flow rules generator...
    spawnTask(() -> generateFlowRules(topologyService.currentTopology(),
            Sets.newHashSet(hostService.getHosts())));
}

From source file:org.smartdeveloperhub.curator.connector.Connector.java

private Connector(final ConnectorConfiguration configuration, final ConversionContext context,
        final MessageIdentifierFactory factory) {
    this.configuration = configuration;
    this.factory = factory;
    this.curatorController = new ClientCuratorController(configuration.curatorConfiguration(),
            "connector-curator", context);
    this.connectorController = new ClientConnectorController(configuration.queueName(),
            configuration.connectorChannel(), context, this.curatorController);
    final ReadWriteLock lock = new ReentrantReadWriteLock();
    this.read = lock.readLock();
    this.write = lock.writeLock();
    this.connected = false;
    this.pendingAcknowledgements = Maps.newConcurrentMap();
    this.activeRequests = Maps.newConcurrentMap();
}

From source file:com.quancheng.saluki.core.registry.internal.AbstractRegistry.java

private void addNotified(GrpcURL subscribedUrl, NotifyListener.NotifyServiceListener listener,
        List<GrpcURL> providerUrls) {
    Map<NotifyListener.NotifyServiceListener, List<GrpcURL>> notifiedUrlMap = notified.get(subscribedUrl);
    List<GrpcURL> notifiedUrlList;
    if (notifiedUrlMap == null) {
        notifiedUrlMap = Maps.newConcurrentMap();
        notifiedUrlList = providerUrls;/*  ww w .  j  a va  2 s. c o  m*/
    } else {
        notifiedUrlList = notifiedUrlMap.get(listener);
        if (notifiedUrlList == null) {
            notifiedUrlList = Lists.newArrayList();
        }
        notifiedUrlList.addAll(providerUrls);
    }
    notifiedUrlMap.putIfAbsent(listener, notifiedUrlList);
    notified.putIfAbsent(subscribedUrl, notifiedUrlMap);
}

From source file:org.onosproject.pi.demo.app.common.AbstractUpgradableFabricApp.java

private void init() {

    // Reset any previous state
    synchronized (this) {
        flowRuleGenerated = Boolean.FALSE;
        leafSwitches = Sets.newHashSet();
        spineSwitches = Sets.newHashSet();
        deviceFlowRules = Maps.newConcurrentMap();
        ruleFlags = Maps.newConcurrentMap();
        pipeconfFlags = Maps.newConcurrentMap();
    }//w w  w  .  j a va  2s.c  o m

    // Schedules a thread that periodically checks the topology, as soon as
    // it corresponds to the expected one, it generates the necessary flow
    // rules and starts the deploy process on each device.
    scheduledExecutorService.scheduleAtFixedRate(this::checkTopologyAndGenerateFlowRules, 0,
            CHECK_TOPOLOGY_INTERVAL_SECONDS, TimeUnit.SECONDS);
}

From source file:com.android.ide.common.blame.MergingLogPersistUtil.java

@NonNull
static Map<SourceFile, SourceFile> loadFromSingleFile(@NonNull File folder, @NonNull String shard) {
    Map<SourceFile, SourceFile> fileMap = Maps.newConcurrentMap();
    JsonReader reader;/*w w  w . java  2  s. c  o  m*/
    File file = getSingleFile(folder, shard);
    if (!file.exists()) {
        return fileMap;
    }
    try {
        reader = new JsonReader(Files.newReader(file, Charsets.UTF_8));
    } catch (FileNotFoundException e) {
        // Shouldn't happen unless it disappears under us.
        return fileMap;
    }
    try {
        reader.beginArray();
        while (reader.peek() != JsonToken.END_ARRAY) {
            reader.beginObject();
            SourceFile merged = SourceFile.UNKNOWN;
            SourceFile source = SourceFile.UNKNOWN;
            while (reader.peek() != JsonToken.END_OBJECT) {
                String name = reader.nextName();
                if (name.equals(KEY_MERGED)) {
                    merged = mSourceFileJsonTypeAdapter.read(reader);
                } else if (name.equals(KEY_SOURCE)) {
                    source = mSourceFileJsonTypeAdapter.read(reader);
                } else {
                    throw new IOException(String.format("Unexpected property: %s", name));
                }
            }
            reader.endObject();
            fileMap.put(merged, source);
        }
        reader.endArray();
        return fileMap;
    } catch (IOException e) {
        // TODO: trigger a non-incremental merge if this happens.
        throw new RuntimeException(e);
    } finally {
        try {
            reader.close();
        } catch (Throwable e) {
            // well, we tried.
        }
    }
}

From source file:org.onosproject.store.primitives.impl.DefaultDatabaseState.java

private Map<String, Versioned<byte[]>> getMap(String mapName) {
    return maps.computeIfAbsent(mapName, name -> Maps.newConcurrentMap());
}