Hazelcast Java Client

With the Java Client for Hazelcast, the fastest open-source caching solution is now available to Java applications in a client-server mode of deployment. Elastically scale Java caching. Hazelcast is an excellent Redis alternative when scaling and speed is of importance.

You can use the native Java client to connect to a Hazelcast cluster. All you need is to add hazelcast.jar into your classpath. hazelcast.jar is already bundled in the Hazelcast standard package.

Quick Start + Download

Quick Start

You can install Hazelcast via Maven. For other options, please check our documentation.

<dependencies>
 <dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast</artifactId>
    <version>$LATEST_VERSION$</version>
 </dependency>
</dependencies>

Downloads

Version Downloads Documentation
Hazelcast IMDG Java Client 5.3.6 (latest)
11/09/2023
Hazelcast IMDG Java Client 5.3.5
10/24/2023
Hazelcast IMDG Java Client 5.3.2
08/21/2023
Hazelcast IMDG Java Client 5.2.5
02/26/2024

For all downloads please see the Download Archives

Previous Releases

Code Samples

package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;

public class MapSample {
    public static void main(String[] args) {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get the Distributed Map from Cluster.
        IMap map = hz.getMap("my-distributed-map");
        //Standard Put and Get.
        map.put("key", "value");
        map.get("key");
        //Concurrent Map methods, optimistic updating
        map.putIfAbsent("somekey", "somevalue");
        map.replace("key", "value", "newvalue");
        // Shutdown this Hazelcast client
        hz.shutdown();
    }
}
Get this code sample on Github
 package client;

import com.hazelcast.cache.ICache;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.AccessedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.expiry.ExpiryPolicy;

public class JCacheSample {

    public static void main(String[] args) {
        // Run as a Hazelcast Client
        System.setProperty("hazelcast.jcache.provider.type", "client");
        // Create the JCache CacheManager
        CacheManager manager = Caching.getCachingProvider().getCacheManager();
        MutableConfiguration configuration = new MutableConfiguration();
        // Expire entries after 1 minute
        configuration.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
        // Get a Cache called "myCache" and configure with 1 minute expiry
        Cache myCache = manager.createCache("myCache", configuration);
        // Put and Get a value from "myCache"
        myCache.put("key", "value");
        String value = myCache.get("key");
        System.out.println(value);
        //ICache is a Hazelcast interface that extends JCache, provides more functionality
        ICache icache = myCache.unwrap(ICache.class);
        //Async Get and Put using ICache interface
        icache.getAsync("key");
        icache.putAsync("key", "value");
        //ICache allows custom expiry per cache entry
        final ExpiryPolicy customExpiryPolicy = AccessedExpiryPolicy.factoryOf(Duration.TEN_MINUTES).create();
        icache.put("key", "newValue", customExpiryPolicy);
        //Size of the Cache should reflect the ICache and JCache operations
        icache.size();
        //Shutdown this Hazelcast Client
        manager.getCachingProvider().close();
    }
}    
Get this code sample on Github
 package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ReplicatedMap;

public class ReplicatedMapSample {

    public static void main(String[] args) {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get a Replicated Map called "my-replicated-map"
        ReplicatedMap map = hz.getReplicatedMap("my-replicated-map");
        // Put and Get a value from the Replicated Map
        String replacedValue = map.put("key", "value");
        // key/value replicated to all members
        System.out.println("replacedValue = " + replacedValue);
        // Will be null as its first update
        String value = map.get("key");
        // the value is retrieved from a random member in the cluster
        System.out.println("value for key = " + value);
        // Shutdown this Hazelcast Client
        hz.shutdown();
    }
}    
Get this code sample on Github
 package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.MultiMap;

import java.util.Collection;

public class MultiMapSample {
    public static void main(String[] args) {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get the Distributed MultiMap from Cluster.
        MultiMap multiMap = hz.getMultiMap("my-distributed-multimap");
        // Put values in the map against the same key
        multiMap.put("my-key", "value1");
        multiMap.put("my-key", "value2");
        multiMap.put("my-key", "value3");
        // Print out all the values for associated with key called "my-key"
        Collection values = multiMap.get("my-key");
        System.out.println(values);
        // remove specific key/value pair
        multiMap.remove("my-key", "value2");
        // Shutdown this Hazelcast Client
        hz.shutdown();
    }
}    
Get this code sample on Github
 package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;

import java.util.Set;

public class SetSample {
    public static void main(String[] args) {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get the Distributed Set from Cluster.
        Set set = hz.getSet("my-distributed-set");
        // Add items to the set with duplicates
        set.add("item1");
        set.add("item1");
        set.add("item2");
        set.add("item2");
        set.add("item2");
        set.add("item3");
        // Get the items. Note that there are no duplicates.
        for (String item: set) {
            System.out.println(item);
        }
        // Shutdown this Hazelcast client
        hz.shutdown();
    }
}
Get this code sample on Github
 package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;

import java.util.List;

public class ListSample {
    public static void main(String[] args) {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get the Distributed List from Cluster.
        List list = hz.getList("my-distributed-list");
        // Add elements to the list
        list.add("item1");
        list.add("item2");
        // Remove the first element
        System.out.println("Removed: " + list.remove(0));
        // There is only one element left
        System.out.println("Current size is " + list.size());
        // Clear the list
        list.clear();
        // Shutdown this Hazelcast client
        hz.shutdown();
    }
}
Get this code sample on Github
 package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class QueueSample {
    public static void main(String[] args) throws InterruptedException {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get a Blocking Queue called "my-distributed-queue"
        BlockingQueue queue = hz.getQueue("my-distributed-queue");
        // Offer a String into the Distributed Queue
        queue.offer("item");
        // Poll the Distributed Queue and return the String
        queue.poll();
        //Timed blocking Operations
        queue.offer("anotheritem", 500, TimeUnit.MILLISECONDS);
        queue.poll(5, TimeUnit.SECONDS);
        //Indefinitely blocking Operations
        queue.put("yetanotheritem");
        System.out.println(queue.take());
        // Shutdown this Hazelcast Client
        hz.shutdown();
    }
}
Get this code sample on Github
package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;

public class TopicSample implements MessageListener {
    @Override
    public void onMessage(Message message) {
        System.out.println("Got message " + message.getMessageObject());
    }

    public static void main(String[] args) {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get a Topic called "my-distributed-topic"
        ITopic topic = hz.getTopic("my-distributed-topic");
        // Add a Listener to the Topic
        topic.addMessageListener(new TopicSample());
        // Publish a message to the Topic
        topic.publish("Hello to distributed world");
        // Shutdown this Hazelcast Client
        hz.shutdown();
    }
}
Get this code sample on Github
 package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.nio.serialization.Portable;
import com.hazelcast.nio.serialization.PortableFactory;
import com.hazelcast.nio.serialization.PortableReader;
import com.hazelcast.nio.serialization.PortableWriter;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.Predicates;
import com.hazelcast.query.SqlPredicate;

import java.io.IOException;
import java.util.Collection;

public class QuerySample {
    public static class User implements Portable {

        public static final int CLASS_ID = 1;

        public String username;
        public int age;
        public boolean active;

        public User(String username, int age, boolean active) {
            this.username = username;
            this.age = age;
            this.active = active;
        }

        public User() {

        }

        @Override
        public String toString() {
            return "User{"
                    + "username='" + username + '\''
                    + ", age=" + age
                    + ", active=" + active
                    + '}';
        }

        @Override
        public int getFactoryId() {
            return ThePortableFactory.FACTORY_ID;
        }

        @Override
        public int getClassId() {
            return CLASS_ID;
        }

        @Override
        public void writePortable(PortableWriter writer) throws IOException {
            writer.writeUTF("username", username);
            writer.writeInt("age", age);
            writer.writeBoolean("active", active);
        }

        @Override
        public void readPortable(PortableReader reader) throws IOException {
            username = reader.readUTF("username");
            age = reader.readInt("age");
            active = reader.readBoolean("active");
        }
    }

    public static class ThePortableFactory implements PortableFactory {

        public static final int FACTORY_ID = 1;

        @Override
        public Portable create(int classId) {
            if (classId == User.CLASS_ID) {
                return new User();
            }
            return null;
        }
    }

    private static void generateUsers(IMap users) {
        users.put("Rod", new User("Rod", 19, true));
        users.put("Jane", new User("Jane", 20, true));
        users.put("Freddy", new User("Freddy", 23, true));
    }

    public static void main(String[] args) {
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.getSerializationConfig()
                .addPortableFactory(ThePortableFactory.FACTORY_ID, new ThePortableFactory());
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient(clientConfig);
        // Get a Distributed Map called "users"
        IMap users = hz.getMap("users");
        // Add some users to the Distributed Map
        generateUsers(users);
        // Create a Predicate from a String (a SQL like Where clause)
        Predicate sqlQuery = new SqlPredicate("active AND age BETWEEN (18 AND 21)");
        // Creating the same Predicate as above but with a builder
        Predicate criteriaQuery = Predicates.and(
                Predicates.equal("active", true),
                Predicates.between("age", 18, 21)
        );
        // Get result collections using the two different Predicates
        Collection result1 = users.values(sqlQuery);
        Collection result2 = users.values(criteriaQuery);
        // Print out the results
        System.out.println(result1);
        System.out.println(result2);
        // Shutdown this Hazelcast Client
        hz.shutdown();
    }
}    
Get this code sample on Github
 package client;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;

import java.util.concurrent.locks.Lock;

public class LockSample {
    public static void main(String[] args) {
        // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
        HazelcastInstance hz = HazelcastClient.newHazelcastClient();
        // Get a distributed lock called "my-distributed-lock"
        Lock lock = hz.getLock("my-distributed-lock");
        // Now create a lock and execute some guarded code.
        lock.lock();
        try {
            //do something here
        } finally {
            lock.unlock();
        }
        // Shutdown this Hazelcast Client
        hz.shutdown();
    }
}
Get this code sample on Github