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

Many things at a time

We have previously seen that Hazelcast provides us with a generic key-value map. However, this capability is popularly used to create a key/list-of-values map. While there is nothing stopping us from defining these ourselves using the 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 by using the specialized MultiMap collection.

Let's have a look at the following example:

public class MultiMapExample {
  public static void main(String[] args) {
    HazelcastInstance hz = Hazelcast.newHazelcastInstance();

    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");
    frCities.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 you can clearly see, using 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 that you should be aware of is that you can't use a Hazelcast map in the pass-by-reference context as you might in a native Java implementation. For example, the following optimization of the previous code will not achieve the desired result:

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

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

主站蜘蛛池模板: 聊城市| 夹江县| 洛扎县| 台东市| 家居| 和龙市| 八宿县| 鄱阳县| 枣阳市| 北碚区| 新源县| 涿鹿县| 孟村| 西乌珠穆沁旗| 大姚县| 收藏| 昌吉市| 峨山| 定兴县| 抚松县| 呼伦贝尔市| 东阿县| 拜泉县| 雷州市| 泰宁县| 扬州市| 肃宁县| 山东省| 古田县| 灵丘县| 类乌齐县| 义马市| 同仁县| 崇左市| 河间市| 万山特区| 宁都县| 茶陵县| 崇信县| 青田县| 牟定县|