Get professional support at Hazelcast.com

Webinar this week: Maximizing Hazelcast Performance with Serialization

The Leading Open Source In-Memory Data Grid:
Distributed Computing, Simplified.

4MB JAR library ⋅ No dependencies ⋅ Apache 2.0 License
Just drop it in your CLASSPATH and start coding.

View Feature List

  • Distributed java.util.{Queue, Set, List, Map}
  • Distributed java.util.concurrency.locks.Lock
  • Distributed java.util.concurrent.ExecutorService
  • Distributed MultiMap for one to many mapping
  • Distributed Topic for publish/subscribe messaging
  • Distributed Indexing and Query support
  • Transaction support and J2EE container integration via JCA
  • Socket level encryption for secure clusters
  • Write-Through and Write-Behind persistence for maps
  • Java Client for accessing the cluster remotely
  • Dynamic HTTP session clustering
  • Support for cluster info and membership events
  • Dynamic discovery
  • Dynamic scaling
  • Dynamic partitioning with backups
  • Dynamic fail-over
  • Web-based cluster monitoring tool
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");
    }
}     
        


Related code samples

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();
    }
}     
        


Related code samples

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");
    }
}


Related code samples

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);
        }
    }
}


Related code samples

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());
    }
}


Related code samples

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();
        }
    }
}


Related code samples

        
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;
        }
    }
}



Related code samples

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;
        }
    }
}


Related code samples

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.mapreduce.aggregation.Aggregations;
import com.hazelcast.mapreduce.aggregation.Supplier;

public class DistributedAggregation {
    public static void main(String[] args) {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);

        IMap<String, Integer> salaries = h.getMap("salaries");
        fillInSalaries(salaries);

        Supplier<String, Integer, Integer> supplier = Supplier.all();
        int sum = salaries.aggregate(supplier, Aggregations.integerSum());
        System.out.println("Aggregated sum: " + sum);
    }
}


        
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.core.IMap;
import com.hazelcast.mapreduce.Collator;
import com.hazelcast.mapreduce.Context;
import com.hazelcast.mapreduce.Job;
import com.hazelcast.mapreduce.JobTracker;
import com.hazelcast.mapreduce.KeyValueSource;
import com.hazelcast.mapreduce.Mapper;
import com.hazelcast.mapreduce.Reducer;
import com.hazelcast.mapreduce.ReducerFactory;

import java.util.Map;

public class MapReduce {
    public static void main(String[] args) throws Exception {
        Config config = new Config();
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);

        IMap<String, Integer> salaries = h.getMap("salaries");
        fillInSalaries(salaries);

        JobTracker jobTracker = h.getJobTracker("salaryTracker");
        KeyValueSource<String, Integer> source = KeyValueSource.fromMap(salaries);

        Job<String, Integer> job = jobTracker.newJob(source);

        ICompletableFuture<Integer> future = job
                .mapper(new SalaryMapper())
                .reducer(new SalaryReducerFactory())
                .submit(new SalaryCollator());

        System.out.println("Aggregated sum: " + future.get());
    }
}

public class SalaryCollator
        implements Collator<Map.Entry<String, Integer>, Integer> {

    @Override
    public Integer collate(Iterable<Map.Entry<String, Integer>> values) {
        int value = 0;
        for (Map.Entry<String, Integer> entry : values) {
            value += entry.getValue();
        }
        return value;
    }
}

public class SalaryMapper
        implements Mapper<String, Integer, String, Integer> {

    @Override
    public void map(String key, Integer value, Context<String, Integer> context) {
        context.emit("salarysum", value);
    }
}


public class SalaryReducerFactory
        implements ReducerFactory<String, Integer, Integer> {

    @Override
    public Reducer<Integer, Integer> newReducer(String key) {
        return new SalaryReducer();
    }

    private static class SalaryReducer
            extends Reducer<Integer, Integer> {

        private volatile int value = 0;

        @Override
        public void reduce(Integer value) {
            this.value += value;
        }

        @Override
        public Integer finalizeReduce() {
            return value;
        }
    }
}      


Related code samples

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();
    }
}


Related code samples

Use Hazelcast for:

NoSQL KV Store

Learn More

Messaging

Learn More

Data Grid

Learn More

Caching

Learn More

Application Scaling

Learn More

Clustering

Learn More

Projects using Hazelcast:

Apache Camel, Apache Shiro, Mulesoft, Vert.x, Alfresco, OrientDB, WS02, Apache Karaf

Is your project using Hazelcast? Let us know!

  • “If you want performance, a simple API, and excellent support, go for Hazelcast.”

    — Atle Prange, Businesscape

  • “@hazelcast grid API is so good and feature complete that I want to cry.
    Perfect for my current needs.”

    — Dmitry Buzdin, @buzdin

We love getting your feedback! Tweet us @Hazelcast or tell us directly!

More Hazelcast Love

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