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:org.polymap.core.data.feature.buffer.LayerFeatureBufferManager.java

/**
 * Gets the buffer manager for the given layer of the current session. If no
 * manager exists yet a new one is created with default buffer type/impl and
 * settings if <code>create</code> is true, otherwise null might be returned.
 * /*from  w  ww.ja va  2s.  c o m*/
 * @param layer
 * @param create True specifies that a new buffer manager is created if
 *        necessary.
 * @return The buffer manager for the given layer.
 */
public static LayerFeatureBufferManager forLayer(ILayer layer, boolean create) {
    assert layer != null;

    ConcurrentMap<String, LayerFeatureBufferManager> managers = Session.instance().managers;
    LayerFeatureBufferManager result = managers.get(layer.id());
    if (result == null && create) {
        result = new LayerFeatureBufferManager(layer);
        LayerFeatureBufferManager prev = managers.putIfAbsent(layer.id(), result);
        result = prev != null ? prev : result;
        assert result.getLayer() == layer;
    }
    return result;
}

From source file:com.networknt.light.rule.validation.AbstractValidationRule.java

public static JsonSchema getSchema(String ruleClass) throws Exception {
    JsonSchema schema = null;/*from   w ww .  ja  v a2  s  . c om*/
    Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) ruleMap.get("cache");
    if (cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        ruleMap.put("cache", cache);
    } else {
        Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
        if (rule != null) {
            schema = (JsonSchema) rule.get("schema");
        }
    }
    if (schema == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            OIndex<?> validationRuleClassIdx = graph.getRawGraph().getMetadata().getIndexManager()
                    .getIndex("Validation.ruleClass");
            OIdentifiable oid = (OIdentifiable) validationRuleClassIdx.get(ruleClass);
            if (oid != null) {
                ODocument validation = (ODocument) oid.getRecord();
                String json = validation.toJSON();
                JsonNode validationNode = ServiceLocator.getInstance().getMapper().readTree(json);
                JsonNode schemaNode = validationNode.get("schema");
                schema = factory.getJsonSchema(schemaNode);
                Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
                if (rule != null) {
                    rule.put("schema", schema);
                } else {
                    rule = new HashMap<String, Object>();
                    rule.put("schema", schema);
                    cache.put(ruleClass, rule);
                }
            } else {
                // could not find the rule validation schema from db. put null in cache so that
                // the next operation won't check db again.
                Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
                if (rule != null) {
                    rule.put("schema", null);
                } else {
                    rule = new HashMap<String, Object>();
                    rule.put("schema", null);
                    cache.put(ruleClass, rule);
                }
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return schema;
}

From source file:xbird.storage.io.RemoteVarSegments.java

public static void handleResponse(final TrackReadRequestMessage request, final ProtocolEncoderOutput out,
        final ConcurrentMap<String, FileChannel> fdCacheMap,
        final ConcurrentMap<String, IDescriptor> directoryCache) throws IOException {
    final String filePath = request.filePath;
    final long[] idxs = request.idxs;
    final int size = idxs.length;

    // look-up directory
    final File dataFile = new File(filePath);
    final long[] offsets = new long[size];
    IDescriptor directory = directoryCache.get(filePath);
    try {/*  ww  w  . j a v  a  2  s.  c o m*/
        if (directory == null) {
            directory = VarSegments.initDescriptor(dataFile);
            directoryCache.put(filePath, directory);
        }
        for (int i = 0; i < size; i++) {
            offsets[i] = directory.getRecordAddr(idxs[i]);
        }
    } catch (IOException e) {
        LOG.error(e);
        throw e;
    }

    FileChannel fileChannel = fdCacheMap.get(filePath);
    if (fileChannel == null) {
        if (!dataFile.exists()) {
            throw new IllegalStateException("file not exists: " + filePath);
        }
        final RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(dataFile, "r");
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
        fileChannel = raf.getChannel();
        fdCacheMap.put(filePath, fileChannel);
    }

    for (int i = 0; i < size; i++) {
        final long offset = offsets[i];
        // get data length
        final ByteBuffer tmpBuf = ByteBuffer.allocate(4);
        try {
            fileChannel.read(tmpBuf, offset);
        } catch (IOException e) {
            LOG.error(e);
            throw e;
        }
        tmpBuf.flip();
        final int length = tmpBuf.getInt();
        tmpBuf.rewind();
        IoBuffer ioBuf = IoBuffer.wrap(tmpBuf);
        out.write(ioBuf);
        // attempt zero-copy sendfile
        long position = offset + 4;
        long count = length;
        FileRegion fileRegion = new DefaultFileRegion(fileChannel, position, count);
        out.write(fileRegion);
    }
}

From source file:org.kuali.rice.krad.data.platform.MaxValueIncrementerFactory.java

/**
 * Either constructs a new incrementer or retrieves a cached instance for the given DataSource and target
 * incrementer name.//  ww w .j  av a  2s .  c o  m
 *
 * @param dataSource the {@link DataSource} for which to retrieve the incrementer.
 * @param incrementerName the case-insensitive name of the incrementer to use, this will generally be the name of
 *        the database object which is used to implement the incrementer.
 * @return an incrementer that can be used to generate the next incremented value for the given incrementer against
 *         the specified {@link DataSource}.
 *
 * @throws IllegalArgumentException if dataSource or incrementerName are null or blank.
 */
public static DataFieldMaxValueIncrementer getIncrementer(DataSource dataSource, String incrementerName) {
    if (dataSource == null) {
        throw new IllegalArgumentException("DataSource must not be null");
    }
    if (StringUtils.isBlank(incrementerName)) {
        throw new IllegalArgumentException("Incrementer name must not be null or blank");
    }

    // yes, we want to check if it's there first, then put if absent, for max speed! This is like ConcurrentMap's
    // version of double-checked locking.
    ConcurrentMap<String, DataFieldMaxValueIncrementer> incrementerCache = cache.get(dataSource);

    if (incrementerCache == null) {
        cache.put(dataSource, new ConcurrentHashMap<String, DataFieldMaxValueIncrementer>(8, 0.9f, 1));
        if (incrementerCache == null) {
            incrementerCache = cache.get(dataSource);
        }
    }

    // now check if we have a cached incrementer
    DataFieldMaxValueIncrementer incrementer = incrementerCache.get(incrementerName.toUpperCase());
    if (incrementer == null) {
        incrementer = incrementerCache.putIfAbsent(incrementerName.toUpperCase(),
                createIncrementer(dataSource, incrementerName));
        if (incrementer == null) {
            incrementer = incrementerCache.get(incrementerName.toUpperCase());
        }
    }
    return incrementer;

}

From source file:de.unentscheidbar.validation.internal.Beans.java

public static <T> T propertyValue(Object bean, String propertyName) {

    try {/*from w  w  w .j  av  a2  s .com*/
        ConcurrentMap<String, MethodHandle> methodHandles = CACHE.get(bean.getClass(),
                new Callable<ConcurrentMap<String, MethodHandle>>() {

                    @Override
                    public ConcurrentMap<String, MethodHandle> call() throws Exception {

                        return new MapMaker().concurrencyLevel(2).makeMap();
                    }
                });
        /*
         * We may assume this map only grows and never shrinks. It does not matter if the same
         * getter is added twice by concurrent invocations of this method.
         */
        MethodHandle getter = methodHandles.get(propertyName);
        if (getter == null) {
            getter = getterMethod(bean.getClass(), propertyName);
            methodHandles.put(propertyName, getter);
        }
        assert getter != null;
        return (T) getter.invoke(bean);
    } catch (Throwable t) {
        throw Throwables.propagate(t);
    }
}

From source file:org.opendaylight.controller.routing.dijkstrav2_implementation.internal.DijkstraImplementation.java

public static Path getRoute(final Node src, final Node dst, final Short Bw,
        ConcurrentMap<Short, DijkstraShortestPath<Node, Edge>> sptBWAware) {
    DijkstraShortestPath<Node, Edge> spt = sptBWAware.get(Bw);
    if (spt == null) {
        return null;
    }//from  w  ww  . ja v a2 s. co m
    List<Edge> path;
    try {
        path = spt.getPath(src, dst);
    } catch (IllegalArgumentException ie) {
        log.debug("A vertex is yet not known between {} {}", src, dst);
        return null;
    }
    Path res;
    try {
        res = new Path(path);
    } catch (ConstructionException e) {
        log.debug("A vertex is yet not known between {} {}", src, dst);
        return null;
    }
    return res;
}

From source file:org.linagora.linshare.webservice.utils.FlowUploaderUtils.java

public static Response testChunk(long chunkNumber, long totalChunks, long chunkSize, long totalSize,
        String identifier, String filename, String relativePath,
        ConcurrentMap<String, ChunkedFile> chunkedFiles, boolean maintenance) {
    if (maintenance) {
        return buildReponse(Status.NO_CONTENT); // 204
        // https://github.com/flowjs/flow.js
        // If this request returns a 200, 201 or 202 HTTP code, the chunks is assumed to have been completed.
        // If request returns a permanent error status, upload is stopped.
        // If request returns anything else, the chunk will be uploaded in the standard fashion.
    }/*from   w  w  w .j  a  v a  2  s  .  c  om*/
    identifier = cleanIdentifier(identifier);
    boolean isValid = isValid(chunkNumber, chunkSize, totalSize, identifier, filename);
    // Throw HTTP 400 error code.
    Validate.isTrue(isValid);
    if (chunkedFiles.containsKey(identifier) && chunkedFiles.get(identifier).hasChunk(chunkNumber)) {
        // HTTP 200 : ok, we already get this chunk.
        return buildReponse(Status.ACCEPTED);
    }
    // HTTP 204 We did not have this chunk
    return buildReponse(Status.NO_CONTENT);
}

From source file:org.opendaylight.controller.routing.dijkstrav2_implementation.internal.DijkstraImplementation.java

private static boolean updateTopo(Edge edge, Short bw, UpdateType type,
        ConcurrentMap<Short, Graph<Node, Edge>> topologyBWAware,
        ConcurrentHashMap<Short, DijkstraShortestPath<Node, Edge>> sptBWAware) {
    Short baseBW = Short.valueOf((short) 0);
    Graph<Node, Edge> topo = topologyBWAware.get(baseBW);
    DijkstraShortestPath<Node, Edge> spt = sptBWAware.get(baseBW);
    boolean edgePresentInGraph = false;

    if (topo == null) {
        // Create topology for this BW
        Graph<Node, Edge> g = new SparseMultigraph();
        topologyBWAware.put(bw, g);/*from  w  w  w.  ja  v a2  s.  c o m*/
        topo = topologyBWAware.get(bw);
        sptBWAware.put(bw, new DijkstraShortestPath(g));
        spt = sptBWAware.get(bw);
    }
    if (topo != null) {
        NodeConnector src = edge.getTailNodeConnector();
        NodeConnector dst = edge.getHeadNodeConnector();
        if (spt == null) {
            spt = new DijkstraShortestPath(topo);
            sptBWAware.put(bw, spt);
        }

        switch (type) {
        case ADDED:
            // Make sure the vertex are there before adding the edge
            topo.addVertex(src.getNode());
            topo.addVertex(dst.getNode());
            // Add the link between
            edgePresentInGraph = topo.containsEdge(edge);
            if (edgePresentInGraph == false) {
                try {
                    topo.addEdge(new Edge(src, dst), src.getNode(), dst.getNode(), EdgeType.DIRECTED);
                } catch (final ConstructionException e) {
                    log.error("", e);
                    return edgePresentInGraph;
                }
            }
        case CHANGED:
            // Mainly raised only on properties update, so not really useful
            // in this case
            break;
        case REMOVED:
            // Remove the edge
            try {
                topo.removeEdge(new Edge(src, dst));
            } catch (final ConstructionException e) {
                log.error("", e);
                return edgePresentInGraph;
            }

            // If the src and dst vertex don't have incoming or
            // outgoing links we can get ride of them
            if (topo.containsVertex(src.getNode()) && (topo.inDegree(src.getNode()) == 0)
                    && (topo.outDegree(src.getNode()) == 0)) {
                log.debug("Removing vertex {}", src);
                topo.removeVertex(src.getNode());
            }

            if (topo.containsVertex(dst.getNode()) && (topo.inDegree(dst.getNode()) == 0)
                    && (topo.outDegree(dst.getNode()) == 0)) {
                log.debug("Removing vertex {}", dst);
                topo.removeVertex(dst.getNode());
            }
            break;
        }
        spt.reset();
        if (bw.equals(baseBW)) {
            //TODO: for now this doesn't work
            //                clearMaxThroughput();
        }
    } else {
        log.error("Cannot find topology for BW {} this is unexpected!", bw);
    }
    return edgePresentInGraph;
}

From source file:com.sm.store.Audience.java

@Override
public void setStoreMap(ConcurrentMap<String, RemoteStore> storeMaps) {
    this.storeMaps = storeMaps;
    this.remoteStore = storeMaps.get(storeName);
    if (remoteStore == null) {
        String error = "can not find store " + storeName + " check the setting of estimateStore in config file";
        logger.error(error);// w ww  . j  av  a2s  .  c om
        throw new RuntimeException(error);
    }
}

From source file:com.github.lightdocs.model.Operation.java

private Parameter getOrCreateParam(String name, ConcurrentMap<String, Parameter> paramMap) {
    Parameter result = paramMap.get(name);
    if (result == null) {
        Parameter newParam = new Parameter(name);
        result = paramMap.putIfAbsent(name, newParam);
        if (result == null) {
            result = newParam;/* w  w  w .  jav a 2  s .co  m*/
        }
    }
    return result;
}