A newer version of Hazelcast Platform is available.

View latest

Start a Local Embedded Cluster

This tutorial introduces you to Hazelcast in an embedded topology. At the end of this tutorial, you’ll know how to start a cluster in your Java application and store data in memory.

Before You Begin

To complete this tutorial, you need the following:

Prerequisites Useful resources

JDK 8+

Maven

Step 1. Set Up the Project

In this step, you’ll set up a Java project that you can later execute to start a Hazelcast cluster and interact with it.

  1. Check that you have Maven installed.

    mvn -v

    If Maven is installed, you should see some information about the Maven installation, which looks similar to the following:

    Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
    Maven home: /usr/local/Cellar/maven/3.8.1/libexec
    Java version: 16.0.1, vendor: Homebrew, runtime: /usr/local/Cellar/openjdk/16.0.1/libexec/openjdk.jdk/Contents/Home
    Default locale: en_GB, platform encoding: UTF-8
    OS name: "mac os x", version: "10.15.7", arch: "x86_64", family: "mac"
  2. Create the following structure in a project directory of your choice.

    📄 pom.xml
    📂 src
      📂 main
        📂 java
          📄 HelloWorld.java
  3. Add the following to your pom.xml file to set your project’s name, version, and its dependencies on external libraries such as Hazelcast.

    Replace the ${jdk.version} placeholder with your JDK version.

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>hz-example</artifactId>
        <version>0.1.0</version>
    
        <dependencies>
            <dependency>
                <groupId>com.hazelcast</groupId>
                <artifactId>hazelcast</artifactId>
                <version>5.2.5</version>
            </dependency>
        </dependencies>
    
        <properties>
            <maven.compiler.source>${jdk.version}</maven.compiler.source>
            <maven.compiler.target>${jdk.version}</maven.compiler.target>
        </properties>
    
    </project>

Step 2. Build a Hazelcast Cluster

Hazelcast clusters consist of servers called members that communicate with each other to form a distributed network. It’s these members that store and process your data in memory.

In this step, you use the Java API to build a three-member cluster called hello-world.

Add the following to your HelloWorld.java file.

package org.example;

(1)
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class HelloWorld {
  public static void main(String[] args) {
    Config helloWorldConfig = new Config();
    helloWorldConfig.setClusterName("hello-world"); (2)

    (3)
    HazelcastInstance hz = Hazelcast.newHazelcastInstance(helloWorldConfig);
    HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(helloWorldConfig);
    HazelcastInstance hz3 = Hazelcast.newHazelcastInstance(helloWorldConfig);
  }
}
1 Import the Hazelcast packages that you’ll need.
2 Configure the name of your Hazelcast cluster.
3 Start three members in your JVM by creating three instances of Hazelcast. A JVM can host multiple Hazelcast members, but each member can be a part of only one cluster.

Now, you can use your Hazelcast members to interact with the Hazelcast API such as by writing data to memory.

Step 3. Write Data to Memory

Hazelcast has lots of distributed data structures available for writing data to memory on your cluster. One of the most popular ways of writing data to memory is to use a distributed map. Maps store key/value pairs called entries, which are replicated and distributed across a cluster.

Write data to a distributed map called my-distributed-map.

  • Map API

  • SQL

Add the following to the bottom of your main method:

Map<String, String> map = hz.getMap("my-distributed-map");
map.put("1", "John");
map.put("2", "Mary");
map.put("3", "Jane");

System.out.println(map.get("1"));
System.out.println(map.get("2"));
System.out.println(map.get("3"));
The Map object is a distributed implementation of a Java map, which extends the standard java.util.Map interface. As a result, you can use the well known map.get() and map.put() methods.

To use SQL in embedded mode, you must add the hazelcast-sql module to your pom.xml file.

<!-- https://mvnrepository.com/artifact/com.hazelcast/hazelcast-sql -->
<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast-sql</artifactId>
    <version>5.2.5</version>
</dependency>

Then, add the following to the bottom of your main() method:

JetConfig jetConfig = helloWorldConfig.getJetConfig();
jetConfig.setEnabled(true); (1)
HazelcastInstance hz = Hazelcast.newHazelcastInstance(helloWorldConfig);

SqlService sql = hz.getSql(); (2)
String createMappingQuery = "CREATE MAPPING myDistributedMap\n"
  + "TYPE IMap\n"
  + "OPTIONS ('keyFormat'='varchar','valueFormat'='varchar')";
// execute mapping query
sql.execute(createMappingQuery);
List<String> insertionQueries = Arrays.asList(
  "SINK INTO myDistributedMap VALUES('1', 'John')",
  "SINK INTO myDistributedMap VALUES('2', 'Mary')",
  "SINK INTO myDistributedMap VALUES('3', 'Jane')"
);
// execute insertion queries
for (String insertionQuery : insertionQueries) {
  sql.execute(insertionQuery);
}
String scanQuery = "SELECT * FROM myDistributedMap";
// execute the select/scan query and print the resulting rows
try (SqlResult result = sql.execute(scanQuery)) {
  int columnCount = result.getRowMetadata().getColumnCount();
  for (SqlRow row : result) {
    for (int colIdx = 0; colIdx < columnCount; colIdx++) {
      System.out.print(row.getObject(colIdx) + " ");
    }
    System.out.println();
  }
}
1 Enable the Jet engine so that you can execute SQL queries on your cluster.
2 Pass your SQL queries to the SQL engine, using the getSql() method.

Step 4. Execute the Program

Use Maven to compile and execute your Java project.

mvn compile exec:java -Dexec.mainClass="org.example.HelloWorld"

You should see something like the following in the console:

Members {size:3, ver:3} [
	Member [192.168.1.164]:5701 - 672970d4-6cc1-48cc-8cfd-f71a1a05f4f6
	Member [192.168.1.164]:5702 - f996e965-32be-4ad6-a623-5f134d632475 this
	Member [192.168.1.164]:5703 - 079d8eed-8516-4137-b569-489666170f07
]

Here, the local IP address of the cluster is 192.168.1.164, and 3 members are running on ports 5701, 5702, and 5703 respectively.

Your members connected to each other automatically to form your hello-world cluster. You can learn more about how members do this in Discovery Mechanisms.

Then, you should see the values in your map:

John
Mary
Jane

To shut down your cluster, press Ctrl+C.

Complete Code Samples

Map API
package org.example;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

import java.util.Map;

public class HelloWorld {
  public static void main(String[] args) {
    Config helloWorldConfig = new Config();
    helloWorldConfig.setClusterName("hello-world");

    HazelcastInstance hz = Hazelcast.newHazelcastInstance(helloWorldConfig);
    HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(helloWorldConfig);
    HazelcastInstance hz3 = Hazelcast.newHazelcastInstance(helloWorldConfig);

    Map<String, String> map = hz.getMap("my-distributed-map");
    map.put("1", "John");
    map.put("2", "Mary");
    map.put("3", "Jane");

    System.out.println(map.get("1"));
    System.out.println(map.get("2"));
    System.out.println(map.get("3"));

  }
}
SQL
package org.example;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.sql.SqlResult;
import com.hazelcast.sql.SqlRow;
import com.hazelcast.sql.SqlService;
import java.util.Arrays;
import java.util.List;

public class HelloWorld {
  public static void main(String[] args) {
    Config helloWorldConfig = new Config();
    helloWorldConfig.setClusterName("hello-world");

    JetConfig jetConfig = helloWorldConfig.getJetConfig();
    jetConfig.setEnabled(true);

    HazelcastInstance hz = Hazelcast.newHazelcastInstance(helloWorldConfig);
    HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(helloWorldConfig);
    HazelcastInstance hz3 = Hazelcast.newHazelcastInstance(helloWorldConfig);

    SqlService sql = hz.getSql();

    String createMappingQuery = "CREATE MAPPING myDistributedMap\n"
            + "TYPE IMap\n"
            + "OPTIONS ('keyFormat'='varchar','valueFormat'='varchar')";
    sql.execute(createMappingQuery);

    List<String> insertionQueries = Arrays.asList(
            "SINK INTO myDistributedMap VALUES('1', 'John')",
            "SINK INTO myDistributedMap VALUES('2', 'Mary')",
            "SINK INTO myDistributedMap VALUES('3', 'Jane')"
    );
    for (String insertionQuery : insertionQueries) {
        sql.execute(insertionQuery);
    }

    String scanQuery = "SELECT * FROM myDistributedMap";
    try (SqlResult result = sql.execute(scanQuery)) {
        int columnCount = result.getRowMetadata().getColumnCount();
        for (SqlRow row : result) {
            for (int colIdx = 0; colIdx < columnCount; colIdx++) {
                System.out.print(row.getObject(colIdx) + " ");
            }
            System.out.println();
        }
    }
  }
}
For more code samples, see this Hazelcast GitHub repository.

Next Steps

Now that you have a local cluster, you can continue your journey with the following tutorials:

If you just want to go straight into deploying a production-ready cluster, see our production checklist.

Explore the tools Hazelcast offers for the following use cases:

Or, if you’re interested in learning more about topics that we introduced in this tutorial, see the following resources: