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:ratpack.sep.exec.InvokeWithRetry.java

private Promise<ActionResults<O>> applyAsync(ExecControl execControl, Action<T, O> action, int retryCount)
        throws Exception {
    return execControl.<Map<String, ActionResult<O>>>promise(fulfiller -> {
        AtomicInteger repeatCounter = new AtomicInteger(1);
        Map<String, ActionResult<O>> results = Maps.newConcurrentMap();
        applyWithRetry(execControl, fulfiller, action, results, repeatCounter);
    }).map(ImmutableMap::copyOf).map(map -> new ActionResults<O>(map)).wiretap(result -> {
        ActionResults<O> actionResults = result.getValue();
        ActionResult<O> actionResult = actionResults.getResults().get(action.getName());
        if (actionResult != null && !"0".equals(actionResult.getCode())) {
            // execute retries asynchronously
            apply(execControl, action, retryCount).defer(Runnable::run).then(retryActionResults -> {
                // TODO: add logging and some special callback
            });/*  w  ww . ja  va  2s .  c  o m*/
        }
    });
}

From source file:org.apache.gobblin.service.modules.flow.BaseFlowToJobSpecCompiler.java

public BaseFlowToJobSpecCompiler(Config config, Optional<Logger> log, boolean instrumentationEnabled) {
    this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
    if (instrumentationEnabled) {
        this.metricContext = Instrumented.getMetricContext(ConfigUtils.configToState(config),
                IdentityFlowToJobSpecCompiler.class);
        this.flowCompilationSuccessFulMeter = Optional
                .of(this.metricContext.meter(ServiceMetricNames.FLOW_COMPILATION_SUCCESSFUL_METER));
        this.flowCompilationFailedMeter = Optional
                .of(this.metricContext.meter(ServiceMetricNames.FLOW_COMPILATION_FAILED_METER));
        this.flowCompilationTimer = Optional
                .<Timer>of(this.metricContext.timer(ServiceMetricNames.FLOW_COMPILATION_TIMER));
    } else {//from   w  ww .j a v a  2s . co  m
        this.metricContext = null;
        this.flowCompilationSuccessFulMeter = Optional.absent();
        this.flowCompilationFailedMeter = Optional.absent();
        this.flowCompilationTimer = Optional.absent();
    }

    this.topologySpecMap = Maps.newConcurrentMap();
    this.edgeTemplateMap = Maps.newConcurrentMap();
    this.config = config;

    /***
     * ETL-5996
     * For multi-tenancy, the following needs to be added:
     * 1. Change singular templateCatalog to Map<URI, JobCatalogWithTemplates> to support multiple templateCatalogs
     * 2. Pick templateCatalog from JobCatalogWithTemplates based on URI, and try to resolve JobSpec using that
     */
    try {
        if (this.config.hasPath(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY)
                && StringUtils.isNotBlank(
                        this.config.getString(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY))) {
            Config templateCatalogCfg = config.withValue(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY,
                    this.config.getValue(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY));
            this.templateCatalog = Optional.of(new FSJobCatalog(templateCatalogCfg));
        } else {
            this.templateCatalog = Optional.absent();
        }
    } catch (IOException e) {
        throw new RuntimeException(
                "Could not initialize FlowCompiler because of " + "TemplateCatalog initialization failure", e);
    }
}

From source file:org.apache.gobblin.metrics.MetricContext.java

protected MetricContext(String name, MetricContext parent, List<Tag<?>> tags, boolean isRoot)
        throws NameConflictException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(name));

    this.closer = Closer.create();

    try {//from w  w  w . jav a 2 s. com
        this.innerMetricContext = this.closer.register(new InnerMetricContext(this, name, parent, tags));
    } catch (ExecutionException ee) {
        throw Throwables.propagate(ee);
    }

    this.contextAwareMetricsSet = Sets.newConcurrentHashSet();

    this.notificationTargets = Maps.newConcurrentMap();
    this.executorServiceOptional = Optional.absent();

    this.notificationTimer = new ContextAwareTimer(this, GOBBLIN_METRICS_NOTIFICATIONS_TIMER_NAME);
    register(this.notificationTimer);

    if (!isRoot) {
        RootMetricContext.get().addMetricContext(this);
    }
}

From source file:com.scistor.queryrouter.server.impl.JdbcHandlerImpl.java

@Override
public Map<String, String> queryForMeta(String tableName) {
    long begin = System.currentTimeMillis();
    Map<String, String> result = Maps.newConcurrentMap();
    Connection conn = null;//from  w  ww. j  a v  a  2  s  .  c  o  m
    PreparedStatement pst = null;
    try {
        conn = this.getJdbcTemplate().getDataSource().getConnection();
        DatabaseMetaData dbMetaData = conn.getMetaData();
        if (StringUtils.isNotEmpty(tableName)) {
            pst = conn.prepareStatement(String.format("select * from %s where 1=2", tableName));
            ResultSetMetaData rsd = pst.executeQuery().getMetaData();
            for (int i = 0; i < rsd.getColumnCount(); i++) {
                result.put(rsd.getColumnName(i + 1), rsd.getColumnTypeName(i + 1));
            }
        }
    } catch (SQLException e1) {
        logger.error("queryId:{} select meta error:{}", 1, e1.getCause().getMessage());
    } finally {
        JdbcUtils.closeConnection(conn);
        JdbcUtils.closeStatement(pst);
        logger.info("queryId:{} select meta cost:{} ms resultsize:{}", 1, System.currentTimeMillis() - begin,
                result.size());
    }
    return result;
}

From source file:org.onosproject.cpman.impl.ControlPlaneMonitor.java

@Activate
public void activate() {
    cpuMetrics = genMDbBuilder(DEFAULT_RESOURCE, Type.CPU, CPU_METRICS);
    memoryMetrics = genMDbBuilder(DEFAULT_RESOURCE, Type.MEMORY, MEMORY_METRICS);
    controlMessageMap = Maps.newConcurrentMap();
    diskMetricsMap = Maps.newConcurrentMap();
    networkMetricsMap = Maps.newConcurrentMap();

    cpuBuf = Maps.newConcurrentMap();/*from  w  w w .  j  ava 2s  . com*/
    memoryBuf = Maps.newConcurrentMap();
    diskBuf = Maps.newConcurrentMap();
    networkBuf = Maps.newConcurrentMap();
    ctrlMsgBuf = Maps.newConcurrentMap();

    availableResourceMap = Maps.newConcurrentMap();
    availableDeviceIdSet = Sets.newConcurrentHashSet();

    communicationService.<ControlMetricsRequest, ControlLoadSnapshot>addSubscriber(CONTROL_STATS,
            SERIALIZER::decode, this::handleMetricsRequest, SERIALIZER::encode);

    communicationService.<ControlResourceRequest, Set<String>>addSubscriber(CONTROL_RESOURCE,
            SERIALIZER::decode, this::handleResourceRequest, SERIALIZER::encode);

    log.info("Started");
}

From source file:org.onosproject.simplefabric.SimpleFabricL2Forward.java

private void refresh() {
    log.debug("simple fabric l2forward refresh");

    Map<Key, SinglePointToMultiPointIntent> newBctIntentsMap = Maps.newConcurrentMap();
    Map<Key, MultiPointToSinglePointIntent> newUniIntentsMap = Maps.newConcurrentMap();

    for (L2Network l2Network : simpleFabric.getL2Networks()) {
        // scans all l2network regardless of dirty flag
        // if l2Network.l2Forward == false or number of interfaces() < 2, no Intents generated
        for (SinglePointToMultiPointIntent intent : buildBrcIntents(l2Network)) {
            newBctIntentsMap.put(intent.key(), intent);
        }//from  ww  w  .  j  a va2 s .  c o m
        for (MultiPointToSinglePointIntent intent : buildUniIntents(l2Network, hostsFromL2Network(l2Network))) {
            newUniIntentsMap.put(intent.key(), intent);
        }
        if (l2Network.dirty()) {
            l2Network.setDirty(false);
        }
    }

    boolean bctUpdated = false;
    for (SinglePointToMultiPointIntent intent : bctIntentsMap.values()) {
        SinglePointToMultiPointIntent newIntent = newBctIntentsMap.get(intent.key());
        if (newIntent == null) {
            log.info("simple fabric l2forward withdraw broadcast intent: {}", intent.key().toString());
            toBePurgedIntentKeys.add(intent.key());
            intentService.withdraw(intent);
            bctUpdated = true;
        }
    }
    for (SinglePointToMultiPointIntent intent : newBctIntentsMap.values()) {
        SinglePointToMultiPointIntent oldIntent = bctIntentsMap.get(intent.key());
        if (oldIntent == null || !oldIntent.filteredEgressPoints().equals(intent.filteredEgressPoints())
                || !oldIntent.filteredIngressPoint().equals(intent.filteredIngressPoint())
                || !oldIntent.selector().equals(intent.selector())
                || !oldIntent.treatment().equals(intent.treatment())
                || !oldIntent.constraints().equals(intent.constraints())) {
            log.info("simple fabric l2forward submit broadcast intent: {}", intent.key().toString());
            toBePurgedIntentKeys.remove(intent.key());
            intentService.submit(intent);
            bctUpdated = true;
        }
    }

    boolean uniUpdated = false;
    for (MultiPointToSinglePointIntent intent : uniIntentsMap.values()) {
        MultiPointToSinglePointIntent newIntent = newUniIntentsMap.get(intent.key());
        if (newIntent == null) {
            log.info("simple fabric l2forward withdraw unicast intent: {}", intent.key().toString());
            toBePurgedIntentKeys.add(intent.key());
            intentService.withdraw(intent);
            uniUpdated = true;
        }
    }
    for (MultiPointToSinglePointIntent intent : newUniIntentsMap.values()) {
        MultiPointToSinglePointIntent oldIntent = uniIntentsMap.get(intent.key());
        if (oldIntent == null || !oldIntent.filteredEgressPoint().equals(intent.filteredEgressPoint())
                || !oldIntent.filteredIngressPoints().equals(intent.filteredIngressPoints())
                || !oldIntent.selector().equals(intent.selector())
                || !oldIntent.treatment().equals(intent.treatment())
                || !oldIntent.constraints().equals(intent.constraints())) {
            log.info("simple fabric l2forward submit unicast intent: {}", intent.key().toString());
            toBePurgedIntentKeys.remove(intent.key());
            intentService.submit(intent);
            uniUpdated = true;
        }
    }

    if (bctUpdated) {
        bctIntentsMap = newBctIntentsMap;
    }
    if (uniUpdated) {
        uniIntentsMap = newUniIntentsMap;
    }
}

From source file:edu.umich.robot.metamap.MetamapFactory.java

public Metamap build() {
    for (WallDir dir : WallDir.values())
        wallMaps.put(dir, new HashMap<Integer, List<Integer>>());

    for (int index = 0; index < pixelRooms.size(); ++index) {
        int[] xywh = pixelRooms.get(index);

        if (!doorIds.contains(index)) {
            add(WallDir.NORTH, xywh[1], index);
            add(WallDir.EAST, xywh[0] + xywh[2], index);
            add(WallDir.SOUTH, xywh[1] + xywh[3], index);
            add(WallDir.WEST, xywh[0], index);
        }/* w  w w  .j  a  va  2 s  .  c  o m*/

        RectArea.Builder ab = new RectArea.Builder(xywh, u.getMeters_xywh(xywh), idg);
        absMap.put(index, ab);
        idsMap.put(ab.getId(), ab);
    }

    for (int index = 0; index < pixelRooms.size(); ++index) {
        // RectArea.Builder ab = absMap.get(index);

        int[] xywh = pixelRooms.get(index);
        logger.debug("Room " + index);
        setToList(absMap, index, WallDir.WEST, xywh[0], 1, xywh);
        setToList(absMap, index, WallDir.EAST, xywh[0] + xywh[2], 1, xywh);
        setToList(absMap, index, WallDir.NORTH, xywh[1], 0, xywh);
        setToList(absMap, index, WallDir.SOUTH, xywh[1] + xywh[3], 0, xywh);
    }

    Map<Integer, Door> doors = Maps.newConcurrentMap();
    for (Integer id : doorIds) {
        RectArea.Builder ab = absMap.get(id);
        int[] xywh = pixelRooms.get(id);

        Door door = new Door(id, u.getMeters_xywh(xywh));
        Integer code = lockedCodes.get(id);
        if (code != null) {
            door.setState(State.LOCKED);
            door.setCode(code);
        } else if (closedIds.contains(id)) {
            door.setState(State.CLOSED);
        }
        doors.put(id, door);

        ab.property("type", "door");

        logger.debug("Door: " + id);
        // determine direction, will be bigger
        if (xywh[2] > xywh[3]) {
            // width is larger: door runs north/south
            gateways(WallDir.NORTH, ab, door);
            gateways(WallDir.SOUTH, ab, door);
        } else {
            // east/west
            gateways(WallDir.EAST, ab, door);
            gateways(WallDir.WEST, ab, door);
        }
    }

    ImmutableList.Builder<AreaDescription> areaList = new ImmutableList.Builder<AreaDescription>();
    for (int i = 0; i < absMap.size(); ++i)
        areaList.add(absMap.get(i).build());

    idg.mark();
    return new Metamap(imagePath, metersPerPixel, origin, areaList.build(), new VirtualObjectManager(oc, idg),
            doors, idg);
}

From source file:com.arpnetworking.metrics.common.tailer.FilePositionStore.java

private FilePositionStore(final Builder builder) {
    _file = builder._file;//from  www. j  av  a 2s.  c o m
    _flushInterval = builder._flushInterval;
    _flushThreshold = builder._flushThreshold;
    _retention = builder._retention;

    ConcurrentMap<String, Descriptor> state = Maps.newConcurrentMap();
    try {
        state = OBJECT_MAPPER.readValue(_file.toFile(), STATE_MAP_TYPE_REFERENCE);
    } catch (final IOException e) {
        LOGGER.warn().setMessage("Unable to load state").addData("file", _file).setThrowable(e).log();
    }
    _state = state;
}

From source file:ch.ethz.bsse.saf.utils.Utils.java

public static Map<String, Read> parseBAMSAMPure(String location) {
    File bam = new File(location);
    final ConcurrentMap<String, Read> readMap;
    System.out.println("");
    try (SAMFileReader sfr = new SAMFileReader(bam)) {
        StatusUpdate.getINSTANCE().print("Parsing alignment");
        readMap = Maps.newConcurrentMap();
        Parallel.ForEach(sfr, new LoopBody<SAMRecord>() {
            @Override//from  w ww . ja  va  2 s . c  om
            public void run(SAMRecord r) {
                ReadTMP read = SFRComputing.single(r);
                if (read != null) {
                    String name = read.name;
                    boolean hasQuality = read.hasQuality;
                    if (readMap.containsKey(name)) {
                        if (hasQuality) {
                            readMap.get(name).setPairedEnd(read.readBases, read.refStart,
                                    read.refStart + read.readBases.length, read.quality, read.cigar,
                                    read.insertions);
                        } else {
                            readMap.get(name).setPairedEnd(read.readBases, read.refStart,
                                    read.refStart + read.readBases.length, read.cigar, read.insertions);
                        }
                        Read r2 = readMap.get(name);
                        if (r2.isPaired()) {
                            //                                sb.append(r2.getCrickEnd() - r2.getWatsonBegin() + "\n");
                            if (Globals.getINSTANCE().isUNPAIRED()) {
                                readMap.put(name + "_R", r2.unpair());
                            } else {
                                if ((r2.getCrickBegin() - r2.getWatsonEnd()) > 2000) {
                                    readMap.put(name + "_R", r2.unpair());
                                }
                            }
                        }
                    } else {
                        if (hasQuality) {
                            readMap.put(name,
                                    new Read(read.readBases, read.refStart,
                                            read.refStart + read.readBases.length, read.quality, read.cigar,
                                            read.insertions));
                        } else {
                            readMap.put(name, new Read(read.readBases, read.refStart,
                                    read.refStart + read.readBases.length, read.cigar, read.insertions));
                        }
                    }
                }
            }
        });
    }
    StatusUpdate.getINSTANCE().print("Parsing alignment\tdone");
    return readMap;
}

From source file:org.apache.giraph.metrics.NoOpMetricsRegistry.java

@Override
protected ConcurrentMap<MetricName, Metric> newMetricsMap() {
    return Maps.newConcurrentMap();
}