Example usage for java.util.concurrent ConcurrentMap put

List of usage examples for java.util.concurrent ConcurrentMap put

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentMap put.

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

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

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

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

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

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

@Test(dataProvider = "guardedMap")
public void removeConditionally(ConcurrentMap<Integer, Integer> map) {
    map.put(1, 2);
    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   w  w  w . j  a  v a2 s  .  c  o m
}

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

protected void addRule(Map<String, Object> data) throws Exception {
    OrientVertex access = null;//from   ww w.  ja v a2s .c  o  m
    String ruleClass = (String) data.get("ruleClass");
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex createUser = graph.getVertexByKey("User.userId", data.remove("createUserId"));
        OrientVertex rule = graph.addVertex("class:Rule", data);
        createUser.addEdge("Create", rule);
        if (rule != null) {
            // add the rule into compile map
            Map<String, Object> compileMap = ServiceLocator.getInstance().getMemoryImage("compileMap");
            ConcurrentMap<String, String> cache = (ConcurrentMap<String, String>) compileMap.get("cache");
            if (cache == null) {
                cache = new ConcurrentLinkedHashMap.Builder<String, String>().maximumWeightedCapacity(10000)
                        .build();
                compileMap.put("cache", cache);
            }
            cache.put(ruleClass, (String) data.get("sourceCode"));
        }

        // For all the newly added rules, the default security access is role based and only
        // owner can access. For some of the rules, like getForm, getMenu, they are granted
        // to anyone in the db script. Don't overwrite if access exists for these rules.

        // check if access exists for the ruleClass and add access if not.
        if (getAccessByRuleClass(ruleClass) == null) {
            access = graph.addVertex("class:Access");
            access.setProperty("ruleClass", ruleClass);
            if (ruleClass.contains("Abstract") || ruleClass.contains("_")) {
                access.setProperty("accessLevel", "N"); // abstract rule and internal beta tester rule
            } else if (ruleClass.endsWith("EvRule")) {
                access.setProperty("accessLevel", "A"); // event rule can be only called internally.
            } else {
                access.setProperty("accessLevel", "R"); // role level access
                List roles = new ArrayList();
                roles.add("owner"); // give owner access for the rule by default.
                access.setProperty("roles", roles);
            }
            access.setProperty("createDate", data.get("createDate"));
            createUser.addEdge("Create", access);
        }
        graph.commit();

        if (access != null) {
            Map<String, Object> accessMap = ServiceLocator.getInstance().getMemoryImage("accessMap");
            ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) accessMap.get("cache");
            if (cache == null) {
                cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000)
                        .build();
                accessMap.put("cache", cache);
            }
            cache.put(ruleClass,
                    mapper.readValue(access.getRecord().toJSON(), new TypeReference<HashMap<String, Object>>() {
                    }));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}

From source file:kieker.tools.bridge.cli.CLIServerMain.java

/**
 * Read the CLI server Kieker classes to id mapping file.
 *
 * @param libraries/* www. j a  v a 2s.c  om*/
 *            array representing a list of library files (*.jar)
 * @param filename
 *            the path of the mapping file.
 *
 * @return a complete IMonitoringRecord to id mapping
 * @throws IOException
 *             If one or more of the given library URLs is somehow invalid or one of the given files could not be accessed.
 */
@SuppressWarnings("unchecked")
private static ConcurrentMap<Integer, Class<? extends IMonitoringRecord>> readMapping(final String[] libraries,
        final String filename) throws IOException {
    final ConcurrentMap<Integer, Class<? extends IMonitoringRecord>> map = new ConcurrentHashMap<Integer, Class<? extends IMonitoringRecord>>();
    final URL[] urls = new URL[libraries.length];
    for (int i = 0; i < libraries.length; i++) {
        urls[i] = new File(libraries[i]).toURI().toURL();
    }

    final PrivilegedClassLoaderAction action = new PrivilegedClassLoaderAction(urls);
    classLoader = AccessController.doPrivileged(action);

    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
        String line = null;
        do {
            try {
                line = in.readLine();
                if (line != null) {
                    final String[] pair = line.split("=");
                    if (pair.length == 2) {
                        // loadClass returns objects of type Class<?> while we only accept Class<? extends IMonitoringRecord> at the moment. This causes an
                        // warning which
                        // is suppressed by the SuppressWarning annotation.
                        map.put(Integer.parseInt(pair[0]),
                                (Class<IMonitoringRecord>) classLoader.loadClass(pair[1]));
                    }
                }
            } catch (final ClassNotFoundException e) {
                CLIServerMain.getLog().warn("Could not load class", e);
            }
        } while (line != null);
    } finally {
        if (in != null) {
            in.close();
        }
    }

    return map;
}

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

protected void impRule(Map<String, Object> data) throws Exception {
    String ruleClass = (String) data.get("ruleClass");
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {// w w w .ja  v a 2  s  .  c  o m
        graph.begin();
        Vertex rule = graph.getVertexByKey("Rule.ruleClass", ruleClass);
        boolean toCompile = true;
        // remove the existing rule if there is.
        if (rule != null) {
            graph.removeVertex(rule);
            // This is to replace existing rule in memory but due to class loader issue, the
            // new rule will replace the old one after restart the server. don't compile it.
            toCompile = false;
        }
        // create a new rule
        Vertex createUser = graph.getVertexByKey("User.userId", data.remove("createUserId"));
        rule = graph.addVertex("class:Rule", data);
        createUser.addEdge("Create", rule);

        if (rule != null && toCompile) {
            // add the rule into compile map
            Map<String, Object> compileMap = ServiceLocator.getInstance().getMemoryImage("compileMap");
            ConcurrentMap<String, String> cache = (ConcurrentMap<String, String>) compileMap.get("cache");
            if (cache == null) {
                cache = new ConcurrentLinkedHashMap.Builder<String, String>().maximumWeightedCapacity(10000)
                        .build();
                compileMap.put("cache", cache);
            }
            cache.put(ruleClass, (String) data.get("sourceCode"));
        }

        // For all the newly added rules, the default security access is role based and only
        // owner can access. For some of the rules, like getForm, getMenu, they are granted
        // to anyone in the db script. Don't overwrite if access exists for these rules.
        // Also, if ruleClass contains "Abstract" then its access level should be N.

        // check if access exists for the ruleClass and add access if not.
        OrientVertex access = null;
        if (getAccessByRuleClass(ruleClass) == null) {
            access = graph.addVertex("class:Access");
            access.setProperty("ruleClass", ruleClass);
            if (ruleClass.contains("Abstract") || ruleClass.contains("_")) {
                access.setProperty("accessLevel", "N"); // abstract and internal beta tester rule
            } else if (ruleClass.endsWith("EvRule")) {
                access.setProperty("accessLevel", "A"); // event rule can be only called internally.
            } else {
                access.setProperty("accessLevel", "R"); // role level access
                List roles = new ArrayList();
                roles.add("owner"); // give owner access for the rule by default.
                access.setProperty("roles", roles);
            }
            access.setProperty("createDate", data.get("createDate"));
        }
        graph.commit();

        if (access != null) {
            Map<String, Object> accessMap = ServiceLocator.getInstance().getMemoryImage("accessMap");
            ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) accessMap.get("cache");
            if (cache == null) {
                cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000)
                        .build();
                accessMap.put("cache", cache);
            }
            cache.put(ruleClass,
                    mapper.readValue(access.getRecord().toJSON(), new TypeReference<HashMap<String, Object>>() {
                    }));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestAppManager.java

public RMContext mockRMContext(int n, long time) {
    final List<RMApp> apps = newRMApps(n, time, RMAppState.FINISHED);
    final ConcurrentMap<ApplicationId, RMApp> map = Maps.newConcurrentMap();
    for (RMApp app : apps) {
        map.put(app.getApplicationId(), app);
    }/* ww w  .  j  a  va2  s .com*/
    Dispatcher rmDispatcher = new AsyncDispatcher();
    ContainerAllocationExpirer containerAllocationExpirer = new ContainerAllocationExpirer(rmDispatcher);
    AMLivelinessMonitor amLivelinessMonitor = new AMLivelinessMonitor(rmDispatcher);
    AMLivelinessMonitor amFinishingMonitor = new AMLivelinessMonitor(rmDispatcher);
    RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class);
    RMContext context = new RMContextImpl(rmDispatcher, containerAllocationExpirer, amLivelinessMonitor,
            amFinishingMonitor, null, null, null, null, null) {
        @Override
        public ConcurrentMap<ApplicationId, RMApp> getRMApps() {
            return map;
        }
    };
    ((RMContextImpl) context).setStateStore(mock(RMStateStore.class));
    metricsPublisher = mock(SystemMetricsPublisher.class);
    context.setSystemMetricsPublisher(metricsPublisher);
    context.setRMApplicationHistoryWriter(writer);
    return context;
}

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

/**
 * Adds schema node when different revision of node has received.
 *
 * @param schemaNode schema node//from  ww w.j a v  a  2 s .c  om
 */
private void addToSchemaStore(YangSchemaNode schemaNode) {

    String date = getDateInStringFormat(schemaNode);
    String name = schemaNode.getName();
    String revName = name;
    if (date != null) {
        revName = name + AT + date;
    }
    //check if already present.
    if (!yangSchemaStore.containsKey(name)) {
        ConcurrentMap<String, YangSchemaNode> revStore = new ConcurrentHashMap<>();
        revStore.put(revName, schemaNode);
        yangSchemaStore.put(name, revStore);
    } else {
        yangSchemaStore.get(name).put(revName, schemaNode);
    }
}

From source file:org.onosproject.store.trivial.impl.SimpleGroupStore.java

/**
 * Updates the existing group entry with the information
 * from group description.//ww w  .ja  v a2  s. c o  m
 *
 * @param deviceId the device ID
 * @param oldAppCookie the current group key
 * @param type update type
 * @param newBuckets group buckets for updates
 * @param newAppCookie optional new group key
 */
@Override
public void updateGroupDescription(DeviceId deviceId, GroupKey oldAppCookie, UpdateType type,
        GroupBuckets newBuckets, GroupKey newAppCookie) {
    // Check if a group is existing with the provided key
    Group oldGroup = getGroup(deviceId, oldAppCookie);
    if (oldGroup == null) {
        return;
    }

    List<GroupBucket> newBucketList = getUpdatedBucketList(oldGroup, type, newBuckets);
    if (newBucketList != null) {
        // Create a new group object from the old group
        GroupBuckets updatedBuckets = new GroupBuckets(newBucketList);
        GroupKey newCookie = (newAppCookie != null) ? newAppCookie : oldAppCookie;
        GroupDescription updatedGroupDesc = new DefaultGroupDescription(oldGroup.deviceId(), oldGroup.type(),
                updatedBuckets, newCookie, oldGroup.appId());
        StoredGroupEntry newGroup = new DefaultGroup(oldGroup.id(), updatedGroupDesc);
        newGroup.setState(GroupState.PENDING_UPDATE);
        newGroup.setLife(oldGroup.life());
        newGroup.setPackets(oldGroup.packets());
        newGroup.setBytes(oldGroup.bytes());
        // Remove the old entry from maps and add new entry using new key
        ConcurrentMap<GroupKey, StoredGroupEntry> keyTable = getGroupKeyTable(oldGroup.deviceId());
        ConcurrentMap<GroupId, StoredGroupEntry> idTable = getGroupIdTable(oldGroup.deviceId());
        keyTable.remove(oldGroup.appCookie());
        idTable.remove(oldGroup.id());
        keyTable.put(newGroup.appCookie(), newGroup);
        idTable.put(newGroup.id(), newGroup);
        notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, newGroup));
    }
}

From source file:com.example.hp.smartstor.CloudMusicManager.uamp.model.MusicProvider.java

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

    for (com.example.hp.smartstor.CloudMusicManager.uamp.model.MutableMediaMetadata m : mMusicListById
            .values()) {/*from  ww  w.jav  a  2  s  .c o  m*/
        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;
}