Open Gitter Chat
Introducing Hazelcast Jet: In-Memory Streaming and Fast Batch Processing. Try it now!
Fork this code on Github

Hazelcast IMDG

The Leading Open Source In-Memory Data Grid:

Distributed Computing, Simplified.

In-Memory Data Grid ⋅ JCache Provider ⋅ Apache 2 License
Small jar with minimal dependencies ⋅

  • Full-featured IMDG

  • JCache Provider

  • Apache 2 License

  • Small JAR with Minimal Dependencies

  • Embedded or Client Server

  • API with Multiple Language Clients

Get Started with these Code Samples:

  • Map
  • JCache
  • EntryProcessor
  • Executor Service
  • Query
  • MultiMap
  • Queue
  • Topic
  • Lock
  • ReplicatedMap
  • IAtomicLong
  • Ringbuffer
Disable Code Wrap
Enable Code Wrap

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
 
import java.util.concurrent.ConcurrentMap;
 
public class DistributedMap {
    public static void main(String[] args) {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        ConcurrentMap<String, String> map = h.getMap("my-distributed-map");
        map.put("key", "value");
        map.get("key");
         
        //Concurrent Map methods
        map.putIfAbsent("somekey", "somevalue");
        map.replace("key", "value", "newvalue");
    }
}    

Browse related code samples on Github


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

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

public class DistributedQueue {
    public static void main(String[] args) throws InterruptedException {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        BlockingQueue<String> queue = h.getQueue("my-distributed-queue");
        queue.offer("item");
        String item = queue.poll();

        //Timed blocking Operations
        queue.offer("anotheritem", 500, TimeUnit.MILLISECONDS);
        String anotherItem = queue.poll(5, TimeUnit.SECONDS);

        //Indefinitely blocking Operations
        queue.put("yetanotheritem");
        String yetanother = queue.take();
    }
}     

Browse related code samples on Github


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

import java.util.Collection;

public class DistributedMultiMap {
    public static void main(String[] args) {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        MultiMap<String, String> multiMap = h.getMultiMap("my-distributed-multimap");
        multiMap.put("key", "value1");
        multiMap.put("key", "value2");
        multiMap.put("key", "value3");

        Collection<String> values = multiMap.get("key");

        // remove specific key/value pair
        multiMap.remove("key", "value2");
    }
}

Browse related code samples on Github


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

import java.io.Serializable;

public class DistributedExecutorService {
    public static void main(String[] args) {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        IExecutorService ex = h.getExecutorService("my-distributed-executor");
        ex.submit(new MessagePrinter("message to any node"));
        Member firstMember = h.getCluster().getMembers().iterator().next();
        ex.executeOnMember(new MessagePrinter("message to very first member of the cluster"), firstMember);
        ex.executeOnAllMembers(new MessagePrinter("message to all members in the cluster"));
        ex.executeOnKeyOwner(new MessagePrinter("message to the member that owns the following key"), "key");
    }

    static class MessagePrinter implements Runnable, Serializable {
        final String message;

        MessagePrinter(String message) {
            this.message = message;
        }

        @Override
        public void run() {
            System.out.println(message);
        }
    }
}

Browse related code samples on Github


import com.hazelcast.config.Config;
import com.hazelcast.core.*;

public class DistributedTopic implements MessageListener<String> {
    public static void main(String[] args) {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        ITopic<String> topic = h.getTopic("my-distributed-topic");
        topic.addMessageListener(new DistributedTopic());
        topic.publish("Hello to distributed world");
    }

    @Override
    public void onMessage(Message<String> message) {
        System.out.println("Got message " + message.getMessageObject());
    }
}

Browse related code samples on Github


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

import java.util.concurrent.locks.Lock;

public class DistributedLock {
    public static void main(String[] args) {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        Lock lock = h.getLock("my-distributed-lock");
        lock.lock();
        try {
            //do something here
        } finally {
            lock.unlock();
        }
    }
}

Browse related code samples on Github

       
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.map.AbstractEntryProcessor;

import java.util.Map;         
        
public class EntryProcessorMain {

    public static void main(String[] args) {
        HazelcastInstance hz = Hazelcast.newHazelcastInstance();
        IMap<String, Integer> map = hz.getMap("map");
        map.put("key", 0);
        map.executeOnKey("key", new IncEntryProcessor());
        System.out.println("new value:" + map.get("key"));
    }

    public static class IncEntryProcessor extends AbstractEntryProcessor<String, Integer> {
        @Override
        public Object process(Map.Entry<String, Integer> entry) {
            int oldValue = entry.getValue();
            int newValue = oldValue + 1;
            entry.setValue(newValue);
            return null;
        }
    }
}

Browse related code samples on Github


import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ReplicatedMap;

public class ReplicatedMapSample {

    public static void main(String[] args) {
        HazelcastInstance h = Hazelcast.newHazelcastInstance();
        ReplicatedMap<String, String> map = h.getReplicatedMap("my-replicated-map");
        map.put("key", "value"); // key/value replicated to all members
        map.get("key"); // the value retrieved from local member
    }
}

Browse related code samples on Github


import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IAtomicLong;
import com.hazelcast.core.IFunction;        
        
public class AtomicLongMain {

    public static void main(String[] args) {
        HazelcastInstance hz = Hazelcast.newHazelcastInstance();
        IAtomicLong counter = hz.getAtomicLong("counter");
        counter.addAndGet(3); // value is now 3
        counter.alter(new MultiplyByTwo());//value is now 6
        System.out.println("counter: "+counter.get());
    }

    public static class MultiplyByTwo implements IFunction<Long,Long> {
        @Override
        public Long apply(Long input) {
            return input*2;
        }
    }
}

Browse related code samples on Github


public class Query {
    public static void main(String[] args) {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        IMap<String, User> users = h.getMap("users");

        // Just generate some random users
        generateRandomUsers(users);

        Predicate sqlQuery = new SqlPredicate("active AND age BETWEEN 18 AND 21)");

        Predicate criteriaQuery = Predicates.and(
                Predicates.equal("active", true),
                Predicates.between("age", 18, 21)
        );

        Collection<User> result1 = users.values(sqlQuery);
        Collection<User> result2 = users.values(criteriaQuery);

        System.out.println(result1);
        System.out.println(result2);
    }

    public static class User implements Serializable {
        String username;
        int age;
        boolean active;
    }
}

Browse related code samples on Github


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;
import com.hazelcast.cache.ICache;

public class JCacheSample {

    public static void main(String[] args) {

        CacheManager manager = Caching.getCachingProvider().getCacheManager();
        MutableConfiguration<String, String> configuration = new MutableConfiguration<String, String>();

        configuration.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));

        Cache<String, String> myCache = manager.createCache("myCache", configuration);

        myCache.put("key", "value");
        myCache.get("key");

        //ICache extends Cache interface, provides more functionality
        ICache<String, String> icache = myCache.unwrap(ICache.class);

        icache.getAsync("key");
        icache.putAsync("key", "value");

        final ExpiryPolicy customExpiryPolicy = AccessedExpiryPolicy.factoryOf(Duration.TEN_MINUTES).create();
        icache.put("key", "newValue", customExpiryPolicy);

        //cache size
        icache.size();
    }
}

Browse related code samples on Github


public class Main {

   public static void main(String[] args){
       HazelcastInstance hz = Hazelcast.newHazelcastInstance();
       final Ringbuffer<Integer> rb = hz.getRingbuffer("rb");

       new MyThread(rb).start();

       for(int k=0;k<100;k++){
           rb.add(k);
       }
   }

   private static class MyThread extends Thread {
       private final Ringbuffer<Integer> rb;

       public MyThread(Ringbuffer<Integer> rb) {
           this.rb = rb;
       }

       @Override
       public void run(){
           try {
               long seq = rb.tailSequence();
               for (; ; ) {
                   System.out.println(rb.readOne(seq));
                   seq++;
               }
           }catch (InterruptedException e){
           }
       }
   }
}

Browse related code samples on Github

Use Hazelcast IMDG for:

  • In-Memory Data Grid

    Hazelcast IMDG is often used as an operation memory layer for databases in order to improve performance of applications, to distribute data across servers, clusters and geographies, to ingest data at very high rates, and to manage large data sets.

  • Caching

    Hazelcast IMDG is one of the most popular open source caching solutions ensuring that data is in the right place when it’s needed for optimal performance.

  • Microservices

    Hazelcast IMDG can be used as the operational memory of a Microservices architecture.

  • Web Session Clustering

    Hazelcast IMDG provides web session clustering which maintains user sessions in-memory for redundancy and seamless backup.

  • Messaging

    Hazelcast IMDG has a broadcast messaging system offering a comparable set of features to JMS topics.

  • In-Memory NoSQL

    Hazelcast IMDG is a in-memory NoSQL Key Value store. Increasingly, more and more deployments are seeing the advantages of ever-expanding RAM sizes at lower costs.

  • Application Scaling

    Hazelcast IMDG combines distributed data structures, distributed caching capabilities, elasticity, memcached support, and integration with Spring and Hibernate. These capabilities bring several benefits to enterprise deployments, including the ability to handle thousands of operations per second, prevent the loss of data after crashes, and dynamically scale as new servers are added.

Who's Using Hazelcast IMDG:

Is your project using Hazelcast? Let us know!

Participate in Events and User Groups

See All Upcoming Events

Support from the Core Team

Get professional support from the same people who built the software.

To learn more, visit us at Hazelcast.com/support