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.whitecloud.ron.musicplayer.model.MusicProvider.java

/**
 * Get the list of music tracks from a server and caches the track information
 * for future reference, keying tracks by musicId and grouping by genre.
 *//* w  w w .  ja  v  a  2s.c om*/
//    public void retrieveMediaAsync(final Callback callback, String spotifyId) {
//        LogHelper.d(TAG, "retrieveMediaAsync called");
//        if (mCurrentState == State.INITIALIZED) {
//            // Nothing to do, execute callback immediately
//            callback.onMusicCatalogReady(true, mSongs);
//            return;
//        }
//
//        // Asynchronously load the music catalog in a separate thread
//        new AsyncTask<String, Void, State>() {
//            @Override
//            protected State doInBackground(String... params) {
//                retrieveMedia(params[0]);
//                return mCurrentState;
//            }
//
//            @Override
//            protected void onPostExecute(State current) {
//                if (callback != null) {
//                    callback.onMusicCatalogReady(current == State.INITIALIZED, mSongs);
//                }
//            }
//        }.execute(spotifyId);
//    }

private synchronized void buildListsByGenre() {
    ConcurrentMap<String, List<MediaMetadataCompat>> newMusicListByGenre = new ConcurrentHashMap<>();

    for (MutableMediaMetadata m : mMusicListById.values()) {
        String genre = m.metadata.getString(MediaMetadataCompat.METADATA_KEY_GENRE);
        List<MediaMetadataCompat> list = newMusicListByGenre.get(genre);
        if (list == null) {
            list = new ArrayList<>();
            newMusicListByGenre.put(genre, list);
        }
        list.add(m.metadata);
    }
    mMusicListByGenre = newMusicListByGenre;
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap")
public void replace_whenPopulated(ConcurrentMap<Integer, Integer> map) {
    map.put(1, 2);/* w w  w  . ja va  2  s.  c o  m*/
    assertThat(map.replace(1, 3), is(2));
    assertThat(map.get(1), is(3));
    assertThat(map.size(), is(1));
}

From source file:org.mule.module.logging.MuleLogFactory.java

public Log getInstance(String name) throws LogConfigurationException {
    final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    ConcurrentMap<String, Log> loggerMap = repository.get(ccl == null ? NO_CCL_CLASSLOADER : ccl.hashCode());

    if (loggerMap == null) {
        loggerMap = new ConcurrentHashMap<String, Log>();

        final ConcurrentMap<String, Log> previous = repository
                .putIfAbsent(ccl == null ? NO_CCL_CLASSLOADER : ccl.hashCode(), loggerMap);
        if (previous != null) {
            loggerMap = previous;/*from  ww w .  java  2s. c  o  m*/
        }

        if (ccl != null) {
            // must save a strong ref to the PhantomReference in order for it to stay alive and work
            refs.put(new PhantomReference<ClassLoader>(ccl, referenceQueue), ccl.hashCode());
        }

    }

    Log instance = loggerMap.get(name);

    if (instance == null) {
        Logger logger = LoggerFactory.getLogger(name);
        if (logger instanceof LocationAwareLogger) {
            instance = new MuleLocationAwareLog((LocationAwareLogger) logger);
        } else {
            instance = new MuleLog(logger);
        }
        final Log previous = loggerMap.putIfAbsent(name, instance);
        if (previous != null) {
            // someone got there before us
            instance = previous;
        }
    }

    return instance;
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap")
public void removeConditionally(ConcurrentMap<Integer, Integer> map) {
    map.put(1, 2);//  w ww . ja v a2  s .c o m
    assertThat(map.remove(1, -2), is(false));
    assertThat(map.remove(1, 2), is(true));
    assertThat(map.get(1), is(nullValue()));
    assertThat(map.containsKey(1), is(false));
    assertThat(map.containsValue(2), is(false));
    assertThat(map, is(emptyMap()));
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap")
public void replaceConditionally_whenPopulated(ConcurrentMap<Integer, Integer> map) {
    map.put(1, 2);//  w w  w .  ja  va  2  s . co  m
    assertThat(map.replace(1, 3, 4), is(false));
    assertThat(map.replace(1, 2, 3), is(true));
    assertThat(map.get(1), is(3));
    assertThat(map.size(), is(1));
}

From source file:com.networknt.light.rule.AbstractBfnRule.java

public boolean getBfnPost(Object... objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    String rid = (String) data.get("@rid");
    String host = (String) data.get("host");
    if (rid == null) {
        inputMap.put("result", "@rid is required");
        inputMap.put("responseCode", 400);
        return false;
    }//  w ww. ja  v a2 s. co m
    Integer pageSize = (Integer) data.get("pageSize");
    Integer pageNo = (Integer) data.get("pageNo");
    if (pageSize == null) {
        inputMap.put("result", "pageSize is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    if (pageNo == null) {
        inputMap.put("result", "pageNo is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    String sortDir = (String) data.get("sortDir");
    String sortedBy = (String) data.get("sortedBy");
    if (sortDir == null) {
        sortDir = "desc";
    }
    if (sortedBy == null) {
        sortedBy = "createDate";
    }
    boolean allowPost = false;
    Map<String, Object> payload = (Map<String, Object>) inputMap.get("payload");
    if (payload != null) {
        Map<String, Object> user = (Map<String, Object>) payload.get("user");
        List roles = (List) user.get("roles");
        if (roles.contains("owner")) {
            allowPost = true;
        } else if (roles.contains("admin") || roles.contains("blogAdmin") || roles.contains("blogUser")) {
            if (host.equals(user.get("host"))) {
                allowPost = true;
            }
        }
    }

    // TODO support the following lists: recent, popular, controversial
    // Get the page from cache.
    List<String> list = null;
    Map<String, Object> bfnMap = ServiceLocator.getInstance().getMemoryImage("bfnMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>) bfnMap.get("listCache");
    if (listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        bfnMap.put("listCache", listCache);
    } else {
        list = (List<String>) listCache.get(rid + sortedBy);
    }

    ConcurrentMap<Object, Object> postCache = (ConcurrentMap<Object, Object>) bfnMap.get("postCache");
    if (postCache == null) {
        postCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        bfnMap.put("postCache", postCache);
    }

    if (list == null) {
        // get the list for db
        list = new ArrayList<String>();
        String json = getBfnPostDb(rid, sortedBy);
        if (json != null) {
            // convert json to list of maps.
            List<Map<String, Object>> posts = mapper.readValue(json,
                    new TypeReference<ArrayList<HashMap<String, Object>>>() {
                    });
            for (Map<String, Object> post : posts) {
                String postRid = (String) post.get("rid");
                list.add(postRid);
                post.remove("@rid");
                post.remove("@type");
                post.remove("@version");
                post.remove("@fieldTypes");
                postCache.put(postRid, post);
            }
        }
        listCache.put(rid + sortedBy, list);
    }
    long total = list.size();
    if (total > 0) {
        List<Map<String, Object>> posts = new ArrayList<Map<String, Object>>();
        for (int i = pageSize * (pageNo - 1); i < Math.min(pageSize * pageNo, list.size()); i++) {
            String postRid = list.get(i);
            Map<String, Object> post = (Map<String, Object>) postCache.get(postRid);
            posts.add(post);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", total);
        result.put("posts", posts);
        result.put("allowPost", allowPost);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    } else {
        // there is no post available. but still need to return allowPost
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", 0);
        result.put("allowPost", allowPost);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    }
}

From source file:com.networknt.light.rule.catalog.AbstractCatalogRule.java

public boolean getCatalogProduct(Object... objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    String rid = (String) data.get("@rid");
    String host = (String) data.get("host");
    if (rid == null) {
        inputMap.put("result", "@rid is required");
        inputMap.put("responseCode", 400);
        return false;
    }/*from ww w . j a va 2 s . com*/
    Integer pageSize = (Integer) data.get("pageSize");
    Integer pageNo = (Integer) data.get("pageNo");
    if (pageSize == null) {
        inputMap.put("result", "pageSize is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    if (pageNo == null) {
        inputMap.put("result", "pageNo is required");
        inputMap.put("responseCode", 400);
        return false;
    }
    String sortDir = (String) data.get("sortDir");
    String sortedBy = (String) data.get("sortedBy");
    if (sortDir == null) {
        sortDir = "desc";
    }
    if (sortedBy == null) {
        sortedBy = "createDate";
    }
    boolean allowAdd = false;
    Map<String, Object> payload = (Map<String, Object>) inputMap.get("payload");
    if (payload != null) {
        Map<String, Object> user = (Map<String, Object>) payload.get("user");
        List roles = (List) user.get("roles");
        if (roles.contains("owner")) {
            allowAdd = true;
        } else if (roles.contains("admin") || roles.contains("catalogAdmin")
                || roles.contains("productAdmin")) {
            if (host.equals(user.get("host"))) {
                allowAdd = true;
            }
        }
    }

    // TODO support the following lists: recent, popular
    // Get the page from cache.
    List<String> list = null;
    Map<String, Object> branchMap = ServiceLocator.getInstance().getMemoryImage("branchMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>) branchMap.get("listCache");
    if (listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        branchMap.put("listCache", listCache);
    } else {
        list = (List<String>) listCache.get(rid + sortedBy);
    }

    ConcurrentMap<Object, Object> productCache = (ConcurrentMap<Object, Object>) branchMap.get("productCache");
    if (productCache == null) {
        productCache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000)
                .build();
        branchMap.put("productCache", productCache);
    }

    if (list == null) {
        // get the list for db
        list = new ArrayList<String>();
        String json = getCatalogProductDb(rid, sortedBy);
        if (json != null) {
            // convert json to list of maps.
            List<Map<String, Object>> products = mapper.readValue(json,
                    new TypeReference<ArrayList<HashMap<String, Object>>>() {
                    });
            for (Map<String, Object> product : products) {
                String productRid = (String) product.get("rid");
                list.add(productRid);
                product.remove("@rid");
                product.remove("@type");
                product.remove("@version");
                product.remove("@fieldTypes");
                productCache.put(productRid, product);
            }
        }
        listCache.put(rid + sortedBy, list);
    }
    long total = list.size();
    if (total > 0) {
        List<Map<String, Object>> products = new ArrayList<Map<String, Object>>();
        for (int i = pageSize * (pageNo - 1); i < Math.min(pageSize * pageNo, list.size()); i++) {
            String productRid = list.get(i);
            Map<String, Object> product = (Map<String, Object>) productCache.get(productRid);
            products.add(product);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", total);
        result.put("products", products);
        result.put("allowAdd", allowAdd);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    } else {
        // there is no product available. but still need to return allowAdd
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", 0);
        result.put("allowAdd", allowAdd);
        inputMap.put("result", mapper.writeValueAsString(result));
        return true;
    }
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap")
public void putIfAbsent(ConcurrentMap<Integer, Integer> map) {
    for (Integer i = 0; i < capacity(); i++) {
        assertThat(map.putIfAbsent(i, i), is(nullValue()));
        assertThat(map.putIfAbsent(i, 1), is(i));
        assertThat(map.get(i), is(i));
    }/*  w w  w  .  j a va2 s.  c om*/
    assertThat(map.size(), is(equalTo((int) capacity())));
}

From source file:com.murati.oszk.audiobook.model.MusicProvider.java

private synchronized void buildAlbumList() {
    //TODO: rename album to ebook
    ConcurrentMap<String, List<MediaMetadataCompat>> newAlbumList = new ConcurrentHashMap<>();

    // Add tracks to ebook
    for (MutableMediaMetadata m : mTrackListById.values()) {
        String album = m.metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
        List<MediaMetadataCompat> list = newAlbumList.get(album);
        if (list == null) {
            list = new ArrayList<>();
            newAlbumList.put(album, list);
        }//  w w w  .j  av a 2  s .c o  m
        list.add(m.metadata);
    }

    //Sort Individual ebooks by track numbers
    for (List<MediaMetadataCompat> album : newAlbumList.values()) {
        //MediaMetadataCompat[] sortedOrder = album.toArray(new MediaMetadataCompat[album.size()]);
        java.util.Collections.sort(album, new Comparator<MediaMetadataCompat>() {
            @Override
            public int compare(final MediaMetadataCompat lhs, MediaMetadataCompat rhs) {
                if (lhs.getLong(METADATA_KEY_TRACK_NUMBER) < rhs.getLong(METADATA_KEY_TRACK_NUMBER))
                    return -1;
                return 1;
            }
        });
    }
    mEbookList = newAlbumList;
}

From source file:org.onosproject.yms.app.ysr.DefaultYangSchemaRegistry.java

/**
 * Returns schema node based on the revision.
 *
 * @param name name of the schema node//from   ww w. ja va2  s . c  o  m
 * @return schema node based on the revision
 */
private YangSchemaNode getSchemaNodeUsingSchemaNameWithRev(String name) {
    ConcurrentMap<String, YangSchemaNode> revMap;
    YangSchemaNode schemaNode;
    if (name.contains(AT)) {
        String[] revArray = name.split(AT);
        revMap = yangSchemaStore.get(revArray[0]);
        schemaNode = revMap.get(name);
        if (schemaNode == null) {
            log.error("{} not found.", name);
        }
        return schemaNode;
    }
    if (yangSchemaStore.containsKey(name)) {
        revMap = yangSchemaStore.get(name);
        if (revMap != null && !revMap.isEmpty()) {
            YangSchemaNode node = revMap.get(name);
            if (node != null) {
                return node;
            }
            String revName = getLatestVersion(revMap);
            return revMap.get(revName);
        }
    }
    log.error("{} not found.", name);
    return null;
}