Reader small image

You're reading from  Getting Started with Hazelcast

Product typeBook
Published inAug 2013
Reading LevelBeginner
Publisher
ISBN-139781782167303
Edition1st Edition
Languages
Right arrow
Author (1)
Matthew Johns
Matthew Johns
author image
Matthew Johns

contacted on 6 may '16 ________ Matthew Johns is an agile software engineer and hands-on technical/solution architect; specialising in designing and delivering highly scaled and available distributed systems, with broad experience across the whole stack. He is the solution architect and lead engineer at Sky.
Read more about Matthew Johns

Right arrow

Chapter 2. Getting off the Ground

Simply put, we can think of Hazelcast as a library technology—a JAR file that we bring into our application's classpath, and integrate with in order to harness its data distribution capabilities. Now, there are many ways we could go about setting up an application to use various third-party libraries and dependencies. Most modern IDEs can do this for you. Dependency management or build tools such as Maven, Ant, or Gradle can automate it, and we could sort all of it out ourselves manually. But it's now time to jump in, head first into the deep end. In this chapter, we shall:

  • Download Hazelcast

  • Create a basic application around the technology

  • Explore the various simple storage collections

  • Fetch and search our stored data

  • Set limits and understand what happens when we reach these

Let's get started


First things first, let's create a working directory for our project.

Now, let's navigate to Hazelcast's download page:

www.hazelcast.com/downloads.jsp

The following image shows what the downloading page should look like:

We will use the latest version, in this case Version 2.6.

Note

While there is nothing stopping you working with the enterprise edition, there is nothing within this book that requires it. For our purposes, the community edition will do just fine.

In unpacking the archive, you will find a lib/ directory. This contains the various library JAR files we could use within our application. For now, let's copy lib/hazelcast-2.6.jar to our working directory.

Showing off straightaway


Within the Hazelcast JAR, there is the very useful utility class TestApp. The class name is a little deceptive as it can be used in more ways than just testing, but its greatest offering is that it provides a simple text console for easy access to distributed collections.

To fire this up, we need to run this class using the Hazelcast JAR as the classpath.

$ java -cp hazelcast-2.6.jar com.hazelcast.examples.TestApp

This should bring up a fair amount of verbose logging, but a reassuring section to look for to show that a cluster has been formed is the following code:

Members [1] {
    Member [127.0.0.1]:5701 this
}

This lets us know that a new cluster of one node has been created with the node indicated by this. The configuration that was used to start up this instance is the default one built into the JAR. You can find a copy of it at bin/hazelcast.xml from within the unpacked archive that we downloaded in the previous section. We should now be presented with a basic...

Mapping back to the real world


Having briefly explored Hazelcast's distributed capabilities via a test console, let's have a look at how we are more likely to interact with a cluster in the real world. Let's create a new SimpleMapExample class with a main method to spin up and manipulate a named distributed map called capitals. Hazelcast refers to these named collections as a namespace and must be uniquely named across the cluster.

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.Map;

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

    Map<String, String> capitals = hz.getMap("capitals");
    capitals.put("GB", "London");
    capitals.put("FR", "Paris");
    capitals.put("US", "Washington DC");
    capitals.put("AU", "Canberra");

    System.err.println(
      "Known capital cities: " + capitals.size());

    System.err.println(
      "Capital city...

Sets, lists, and queues


In our previous examples, we have looked at key/value storage provided by Hazelcast maps; however, there are a number of other collections that provide keyless groups of objects. Two of these additional types are distributed versions of collections that we are hopefully already familiar with—sets and lists.

As we know, the primary difference between the two is that lists allow for multiple entries and a set does not. So if we add them to our previous map example, we get the following code:

Set<String> cities = hz.getSet("cities");
cities.addAll(captials.values());
cities.add("London");
cities.add("Rome");
cities.add("New York");

List<String> countries = hz.getList("countries");
countries.addAll(captials.keySet());
countries.add("CA");
countries.add("DE");
countries.add("GB"); // duplicate entry

In using our test console again to interact with these new collections, we will have to use different commands as we are now interacting with a set and a list rather...

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...

Searching and indexing


In moving towards creating clean key/value-based storage, we may find that we have lost some of the extra searching capabilities that traditional databases offer. Mainly that we now can't find records within a dataset without knowing the primary key to that entry. However, fear not, as Hazelcast provides similar capabilities for searching its maps by predefined indexes. These can be either ordered (ascending) or unordered, depending on our particular data needs. But be aware that indexing doesn't come for free; the internal lookup table used to provide the quick searching on reads is maintained as we make changes to the map; this will add latency to every write operation to that namespace.

So firstly, let's create a new plain old Java object (POJO) to represent a city.

import java.io.Serializable;

public class City implements Serializable {
  private String name;
  private String country;
  private int population;

  public City(String name, String country, int population...

What happens when we reach our limits?


As large as we may scale our cluster to handle ever-growing datasets, it is quite possible that we will want to configure a map to feature specific behavior. The main things we can customize the number of backup counts and types, limits on how big a particular map can grow plus what we do when we reach that limit, and defining a default lifespan for our entries. We can use the hazelcast.xml configuration to define this behavior for all maps or for an individual one. Now, we can copy the configuration from the unpacked download bin/hazelcast.xml to our working directory, and add a custom configuration for our capitals map.

<map name="capitals">

  <max-size policy="cluster_wide_map_size">10</max-size>
  <eviction-policy>LFU</eviction-policy>
  <eviction-percentage>20</eviction-percentage>

  <backup-count>1</backup-count>
  <async-backup-count>1</async-backup-count>

  <time-to-live...

Summary


One of Hazelcast's greatest strengths is the ease of getting going with neighbor self-discovery and automatic clustering we can create a basic resilience and consistent data source in minutes. While there is plenty of detail left to cover and simple examples don't paint a full picture, we have hopefully already gained a lot of confidence in the technology. As we move forward, we will explore the increasing specialized functionality and understand your application's individual needs that will dictate how valuable each topic is to you.

In the next chapter, we shall move on a little further, starting to use the more concurrent capabilities on offer.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Getting Started with Hazelcast
Published in: Aug 2013Publisher: ISBN-13: 9781782167303
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Matthew Johns

contacted on 6 may '16 ________ Matthew Johns is an agile software engineer and hands-on technical/solution architect; specialising in designing and delivering highly scaled and available distributed systems, with broad experience across the whole stack. He is the solution architect and lead engineer at Sky.
Read more about Matthew Johns