- Getting Started with Hazelcast
- Mat Johns
- 281字
- 2021-08-06 16:56:52
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.
- MySQL數(shù)據(jù)庫(kù)管理實(shí)戰(zhàn)
- PHP 從入門到項(xiàng)目實(shí)踐(超值版)
- 程序員數(shù)學(xué):用Python學(xué)透線性代數(shù)和微積分
- NLTK基礎(chǔ)教程:用NLTK和Python庫(kù)構(gòu)建機(jī)器學(xué)習(xí)應(yīng)用
- Rust Cookbook
- Instant QlikView 11 Application Development
- 數(shù)據(jù)結(jié)構(gòu)案例教程(C/C++版)
- Java系統(tǒng)化項(xiàng)目開發(fā)教程
- 編程與類型系統(tǒng)
- Babylon.js Essentials
- Advanced Express Web Application Development
- PHP 7從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)
- Docker:容器與容器云(第2版)
- 實(shí)戰(zhàn)Python網(wǎng)絡(luò)爬蟲
- React and React Native