官术网_书友最值得收藏!

Many things at a time

We have seen previously that Hazelcast provides us with a generic key/value map; however, one popular use of this capability would be to create a key/list-of-values map. While there is nothing stopping us from defining these ourselves using standard Java generics, we will have to manually handle the initialization of each key entry. Hazelcast has luckily gone out of its way to make our lives easier by handling this case for us, through the use of the specialized MultiMap collection.

Let's have a look at the following example:

Map<String, List<String>> manualCities = hz.getMap("manualCities");

List<String> gbCities = new ArrayList<String>();
manualCities.put("GB", gbCities);

gbCities = manualCities.get("GB");
gbCities.add("London");
manualCities.put("GB", gbCities);

gbCities = manualCities.get("GB");
gbCities.add("Southampton");
manualCities.put("GB", gbCities);

List<String> frCities = new ArrayList<String>();
manualCities.put("FR", frCities);

frCities = manualCities.get("FR");
manualCities.get("FR").add("Paris");
manualCities.put("FR", frCities);

System.err.println(
  String.format("Manual: GB=%s, FR=%s",
    manualCities.get("GB"),
    manualCities.get("FR")));


MultiMap<String, String> multiMapCities =
  hz.getMultiMap("multiMapCities");

multiMapCities.put("GB", "London");
multiMapCities.put("GB", "Southampton");

multiMapCities.put("FR", "Paris");

System.err.println(
  String.format("MultiMap: GB=%s, FR=%s",
    multiMapCities.get("GB"),
    multiMapCities.get("FR")));

As we can clearly see, the use of MultiMap in this way dramatically simplifies the code as well as allowing you to modify the underlying map using delta changes rather than having to fully retrieve, modify, and persist for what could be a small change in a large list. One important point to be aware of is that we can't use a Hazelcast map in a pass-by-reference context, as we might do with a native Java implementation. For example, the following optimization of the previous code would not achieve the desired result:

manualCities.get("GB").put("Leeds");

This is because Hazelcast always returns a cloned copy of the data rather than the instance actually held; so modifying the returned object as we would in the preceding code does not actually update the persisted value.

主站蜘蛛池模板: 永济市| 黄骅市| 旬邑县| 高雄县| 门源| 西乌| 茂名市| 桐城市| 海淀区| 金塔县| 安乡县| 金秀| 吉安县| 苍梧县| 闻喜县| 上蔡县| 长寿区| 陇川县| 岳阳市| 冕宁县| 唐山市| 嘉禾县| 旌德县| 天镇县| 平定县| 玛纳斯县| 哈巴河县| 郁南县| 上杭县| 灵山县| 周宁县| 广昌县| 赫章县| 平乡县| 长葛市| 华宁县| 丽水市| 安乡县| 申扎县| 昌宁县| 湟中县|