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:com.sworddance.beans.BeanWorker.java

/**
 * @param clazz//from w  w w.j  a  va  2s .com
 * @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.murati.oszk.audiobook.model.MusicProvider.java

private synchronized void addMediaToCategory(MutableMediaMetadata m, String metadata,
        ConcurrentMap<String, List<String>> newListByMetadata) {
    // Get Key//from  w w w  .j av  a  2s  .  c  o  m
    String metaValueString = m.metadata.getString(metadata);

    for (String mv : metaValueString.split(",")) {

        //TODO: Client resource translations
        String key = mv.replaceAll("\\(.*\\)", "");
        if (key.matches("^(\\d+|\\.).*")) { // Numbers or dots
            Log.i(TAG, "Skipping " + key);
            continue;
        }
        key = TextHelper.Capitalize(key);
        // Get List by Key
        List<String> list = newListByMetadata.get(key);
        if (list == null) {
            list = new ArrayList<>();
            newListByMetadata.put(key, list);
        }

        // Add ebook by key
        String ebook = m.metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
        if (!list.contains(ebook)) {
            list.add(ebook);
        }
    }
}

From source file:com.datatorrent.lib.io.fs.AbstractFSWriter.java

@Override
public void teardown() {
    ConcurrentMap<String, FSDataOutputStream> fileMap = streamsCache.asMap();
    List<String> fileNames = new ArrayList<String>();
    int numberOfFailures = 0;
    IOException savedException = null;

    //Close all the streams you can
    for (String seenFileName : streamsCache.asMap().keySet()) {
        FSDataOutputStream outputStream = fileMap.get(seenFileName);

        try {// w  ww .j a v  a 2 s  .  c o m
            outputStream.close();
        } catch (IOException ex) {
            //Count number of failures
            numberOfFailures++;
            //Add names of first N failed files to list
            if (fileNames.size() < MAX_NUMBER_FILES_IN_TEARDOWN_EXCEPTION) {
                fileNames.add(seenFileName);
                //save excpetion
                savedException = ex;
            }
        }
    }

    //Try to close the file system
    boolean fsFailed = false;

    try {
        fs.close();
    } catch (IOException ex) {
        //Closing file system failed
        savedException = ex;
        fsFailed = true;
    }

    //There was a failure closing resources
    if (savedException != null) {
        String errorMessage = "";

        //File system failed to close
        if (fsFailed) {
            errorMessage += "Closing the fileSystem failed. ";
        }

        //Print names of atmost first N files that failed to close
        if (!fileNames.isEmpty()) {
            errorMessage += "The following files failed closing: ";
        }

        for (String seenFileName : fileNames) {
            errorMessage += seenFileName + ", ";
        }

        if (numberOfFailures > MAX_NUMBER_FILES_IN_TEARDOWN_EXCEPTION) {
            errorMessage += (numberOfFailures - MAX_NUMBER_FILES_IN_TEARDOWN_EXCEPTION) + " more files failed.";
        }

        //Fail
        throw new RuntimeException(errorMessage, savedException);
    }

    long currentTimeStamp = System.currentTimeMillis();
    totalTime += currentTimeStamp - lastTimeStamp;
    lastTimeStamp = currentTimeStamp;
}

From source file:com.networknt.light.rule.product.AbstractProductRule.java

protected String searchProduct(Map<String, Object> criteria) throws Exception {
    // first check if the full list is in cache.
    String json = null;//from   w w w.  j a v  a2 s  .c om
    Map<String, Object> result = new HashMap<String, Object>();
    List<ODocument> products = new ArrayList<ODocument>();
    int total = 0;
    String host = (String) criteria.get("host");
    Map<String, Object> productMap = (Map<String, Object>) ServiceLocator.getInstance()
            .getMemoryImage("productMap");
    Map<String, Object> hostMap = (Map<String, Object>) productMap.get(host);
    if (hostMap == null) {
        hostMap = new ConcurrentHashMap<String, Object>(10, 0.9f, 1);
        productMap.put(host, hostMap);
    }
    String key = null;
    String categoryRid = (String) criteria.get("categoryRid");
    if (categoryRid != null) {
        key = categoryRid + criteria.get("sortedBy");
    } else {
        key = "" + criteria.get("sortedBy");
    }
    Integer pageNo = (Integer) criteria.remove("pageNo");
    Integer pageSize = (Integer) criteria.remove("pageSize");
    List<String> list = (List<String>) hostMap.get(key);
    if (list == null) {
        // not in cache, search from db and put them in cache.
        List<ODocument> docs = searchProductDb(criteria);
        total = docs.size();
        int i = 0;
        list = new ArrayList<String>();
        for (ODocument doc : docs) {
            list.add(doc.field("@rid").toString());
            if (i >= pageSize * (pageNo - 1) && i < pageSize * pageNo) {
                products.add(doc);
                i++;
                // put only the current page in cache.
                ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) productMap.get("cache");
                if (cache == null) {
                    cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000)
                            .build();
                    productMap.put("cache", cache);
                }
                cache.put(doc.field("@rid").toString(), doc);
            }
        }
    } else {
        // we have a list of rids.
        total = list.size();
        for (int i = pageSize * (pageNo - 1); i < Math.min(pageSize * pageNo, list.size()); i++) {
            String rid = (String) list.get(i);
            ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) productMap.get("cache");
            ODocument product = (ODocument) cache.get(rid);
            if (product == null) {
                // not in cache, get from db and put it into the cache.
                product = DbService.getODocumentByRid(rid);
                cache.put(rid, product);
            }
            products.add(product);
        }
    }
    if (products != null && products.size() > 0) {
        result.put("total", total);
        result.put("products", OJSONWriter.listToJSON(products, null));
        json = mapper.writeValueAsString(result);
    }
    return json;
}

From source file:org.apache.hadoop.yarn.util.TestFSDownload.java

@Test(timeout = 60000)
public void testDownloadPublicWithStatCache()
        throws IOException, URISyntaxException, InterruptedException, ExecutionException {
    final Configuration conf = new Configuration();
    FileContext files = FileContext.getLocalFSFileContext(conf);
    Path basedir = files.makeQualified(new Path("target", TestFSDownload.class.getSimpleName()));

    // if test directory doesn't have ancestor permission, skip this test
    FileSystem f = basedir.getFileSystem(conf);
    assumeTrue(FSDownload.ancestorsHaveExecutePermissions(f, basedir, null));

    files.mkdir(basedir, null, true);//from  w ww .j  a v  a 2 s.c om
    conf.setStrings(TestFSDownload.class.getName(), basedir.toString());

    int size = 512;

    final ConcurrentMap<Path, AtomicInteger> counts = new ConcurrentHashMap<Path, AtomicInteger>();
    final CacheLoader<Path, Future<FileStatus>> loader = FSDownload.createStatusCacheLoader(conf);
    final LoadingCache<Path, Future<FileStatus>> statCache = CacheBuilder.newBuilder()
            .build(new CacheLoader<Path, Future<FileStatus>>() {
                public Future<FileStatus> load(Path path) throws Exception {
                    // increment the count
                    AtomicInteger count = counts.get(path);
                    if (count == null) {
                        count = new AtomicInteger(0);
                        AtomicInteger existing = counts.putIfAbsent(path, count);
                        if (existing != null) {
                            count = existing;
                        }
                    }
                    count.incrementAndGet();

                    // use the default loader
                    return loader.load(path);
                }
            });

    // test FSDownload.isPublic() concurrently
    final int fileCount = 3;
    List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
    for (int i = 0; i < fileCount; i++) {
        Random rand = new Random();
        long sharedSeed = rand.nextLong();
        rand.setSeed(sharedSeed);
        System.out.println("SEED: " + sharedSeed);
        final Path path = new Path(basedir, "test-file-" + i);
        createFile(files, path, size, rand);
        final FileSystem fs = path.getFileSystem(conf);
        final FileStatus sStat = fs.getFileStatus(path);
        tasks.add(new Callable<Boolean>() {
            public Boolean call() throws IOException {
                return FSDownload.isPublic(fs, path, sStat, statCache);
            }
        });
    }

    ExecutorService exec = Executors.newFixedThreadPool(fileCount);
    try {
        List<Future<Boolean>> futures = exec.invokeAll(tasks);
        // files should be public
        for (Future<Boolean> future : futures) {
            assertTrue(future.get());
        }
        // for each path exactly one file status call should be made
        for (AtomicInteger count : counts.values()) {
            assertSame(count.get(), 1);
        }
    } finally {
        exec.shutdown();
    }
}

From source file:org.onosproject.store.group.impl.DistributedGroupStore.java

private Group getMatchingExtraneousGroupbyId(DeviceId deviceId, Integer groupId) {
    ConcurrentMap<GroupId, Group> extraneousMap = extraneousGroupEntriesById.get(deviceId);
    if (extraneousMap == null) {
        return null;
    }//from   w  w w  .ja  va2  s. c o  m
    return extraneousMap.get(new DefaultGroupId(groupId));
}

From source file:org.onebusaway.transit_data_federation.impl.service_alerts.ServiceAlertsServiceImpl.java

private <T> void updateReferences(ServiceAlert existingServiceAlert, ServiceAlert serviceAlert,
        ConcurrentMap<T, Set<AgencyAndId>> map, AffectsKeyFactory<T> affectsKeyFactory) {

    Set<T> existingEffects = Collections.emptySet();
    if (existingServiceAlert != null) {
        existingEffects = affectsKeyFactory.getKeysForAffects(existingServiceAlert);
    }//from  w  w w . j a  v  a2 s .co  m

    Set<T> newEffects = Collections.emptySet();
    if (serviceAlert != null) {
        newEffects = affectsKeyFactory.getKeysForAffects(serviceAlert);
    }

    for (T existingEffect : existingEffects) {
        if (newEffects.contains(existingEffect))
            continue;
        AgencyAndId id = ServiceAlertLibrary.agencyAndId(existingServiceAlert.getId());
        Set<AgencyAndId> ids = map.get(existingEffect);
        ids.remove(id);
        if (ids.isEmpty())
            map.remove(existingEffect);
    }

    for (T newEffect : newEffects) {
        if (existingEffects.contains(newEffect))
            continue;
        AgencyAndId id = ServiceAlertLibrary.agencyAndId(serviceAlert.getId());
        Set<AgencyAndId> ids = map.get(newEffect);
        if (ids == null) {
            ids = new HashSet<AgencyAndId>();
            map.put(newEffect, ids);
        }
        ids.add(id);
    }
}

From source file:org.apereo.portal.portlet.registry.PortletEntityRegistryImpl.java

@Override
public Lock getPortletEntityLock(HttpServletRequest request, IPortletEntityId portletEntityId) {
    final ConcurrentMap<IPortletEntityId, Lock> lockMap = getPortletEntityLockMap(request);

    //See if the lock already exist, return if it does
    Lock lock = lockMap.get(portletEntityId);
    if (lock != null) {
        return lock;
    }//from   ww w .ja v a 2 s.  c  o m

    //Create a new lock and do a putIfAbsent to avoid synchronizing but still get a single lock instance for the session. 
    lock = createPortletEntityLock();
    return ConcurrentMapUtils.putIfAbsent(lockMap, portletEntityId, lock);
}

From source file:org.opendaylight.ovsdb.plugin.impl.ConfigurationServiceImpl.java

private String getTableNameForRowUuid(Node node, String databaseName, UUID rowUuid) {
    ConcurrentMap<String, ConcurrentMap<String, Row>> cache = ovsdbInventoryService.getCache(node,
            databaseName);/*from w  ww  .j  a  va2  s .c om*/
    if (cache == null)
        return null;
    for (String tableName : cache.keySet()) {
        ConcurrentMap<String, Row> rows = cache.get(tableName);
        if (rows.get(rowUuid.toString()) != null) {
            return tableName;
        }
    }
    return null;
}

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  ww. j a va 2 s  .  c om*/
    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 });
    }
}