In-memory distributed computing platform for real-time stream processing and data storage with SQL capabilities
—
Hazelcast provides a comprehensive set of distributed data structures that are partitioned and replicated across the cluster. These structures provide thread-safe, concurrent access with high availability and fault tolerance.
The IMap is Hazelcast's distributed implementation of java.util.concurrent.ConcurrentMap with additional distributed capabilities.
import com.hazelcast.map.IMap;
import com.hazelcast.map.MapStore;
import com.hazelcast.map.MapLoader;
import com.hazelcast.map.EntryProcessor;
import com.hazelcast.map.listener.MapListener;
import com.hazelcast.query.Predicate;
import com.hazelcast.config.IndexConfig;
import com.hazelcast.config.IndexType;
import com.hazelcast.core.DistributedObject;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CompletionStage;
import java.util.UUID;
import java.util.Set;
import java.util.Collection;
import java.util.Map;
public interface IMap<K, V> extends ConcurrentMap<K, V>, DistributedObject {
// Basic operations
V put(K key, V value);
V put(K key, V value, long ttl, TimeUnit timeunit);
V put(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit);
V putIfAbsent(K key, V value);
V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit);
boolean replace(K key, V oldValue, V newValue);
V replace(K key, V value);
V get(Object key);
V remove(Object key);
boolean remove(Object key, Object value);
void delete(Object key);
void set(K key, V value);
void set(K key, V value, long ttl, TimeUnit timeunit);
// Batch operations
void putAll(Map<? extends K, ? extends V> map);
Map<K, V> getAll(Set<K> keys);
void setAll(Map<? extends K, ? extends V> map);
// Async operations
CompletionStage<V> putAsync(K key, V value);
CompletionStage<V> putAsync(K key, V value, long ttl, TimeUnit timeunit);
CompletionStage<V> getAsync(K key);
CompletionStage<V> removeAsync(K key);
// Querying
Set<K> keySet();
Set<K> keySet(Predicate<K, V> predicate);
Collection<V> values();
Collection<V> values(Predicate<K, V> predicate);
Set<Entry<K, V>> entrySet();
Set<Entry<K, V>> entrySet(Predicate<K, V> predicate);
// Entry processing
<R> R executeOnKey(K key, EntryProcessor<K, V, R> entryProcessor);
<R> Map<K, R> executeOnKeys(Set<K> keys, EntryProcessor<K, V, R> entryProcessor);
<R> Map<K, R> executeOnEntries(EntryProcessor<K, V, R> entryProcessor);
<R> Map<K, R> executeOnEntries(EntryProcessor<K, V, R> entryProcessor, Predicate<K, V> predicate);
// Indexing
void addIndex(IndexType type, String... attributes);
void addIndex(IndexConfig indexConfig);
// Listeners
UUID addEntryListener(MapListener listener, boolean includeValue);
UUID addEntryListener(MapListener listener, K key, boolean includeValue);
UUID addEntryListener(MapListener listener, Predicate<K, V> predicate, boolean includeValue);
boolean removeEntryListener(UUID registrationId);
// Locking
void lock(K key);
void lock(K key, long leaseTime, TimeUnit timeUnit);
boolean isLocked(K key);
boolean tryLock(K key);
boolean tryLock(K key, long time, TimeUnit timeunit);
void unlock(K key);
void forceUnlock(K key);
// Storage operations
void flush();
void evict(K key);
void evictAll();
void clear();
// Statistics and info
LocalMapStats getLocalMapStats();
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
}IMap<String, User> userMap = hz.getMap("users");
// Put operations
User user = new User("john", "john@example.com");
userMap.put("john", user);
// Put with TTL (expires after 30 minutes)
userMap.put("temp-user", user, 30, TimeUnit.MINUTES);
// Put with TTL and max idle time
userMap.put("session-user", user, 1, TimeUnit.HOURS, 30, TimeUnit.MINUTES);
// Conditional operations
User existing = userMap.putIfAbsent("john", user);
boolean replaced = userMap.replace("john", oldUser, newUser);
// Retrieval
User retrieved = userMap.get("john");
boolean exists = userMap.containsKey("john");import com.hazelcast.query.Predicates;
import com.hazelcast.config.IndexType;
// Add index for better query performance
userMap.addIndex(IndexType.SORTED, "age");
userMap.addIndex(IndexType.HASH, "department");
// Query examples
Collection<User> youngUsers = userMap.values(Predicates.lessThan("age", 30));
Set<String> keys = userMap.keySet(Predicates.like("name", "John%"));
// Complex predicates
Predicate<String, User> complexPredicate = Predicates.and(
Predicates.greaterEqual("age", 25),
Predicates.equal("department", "Engineering")
);
Collection<User> engineers = userMap.values(complexPredicate);
// SQL predicates
Collection<User> sqlResult = userMap.values(Predicates.sql("age > 25 AND department = 'Engineering'"));import com.hazelcast.map.EntryProcessor;
// Custom entry processor
public class IncrementCounterProcessor implements EntryProcessor<String, Integer, Integer> {
private int incrementBy;
public IncrementCounterProcessor(int incrementBy) {
this.incrementBy = incrementBy;
}
@Override
public Integer process(Map.Entry<String, Integer> entry) {
Integer currentValue = entry.getValue();
if (currentValue == null) {
currentValue = 0;
}
Integer newValue = currentValue + incrementBy;
entry.setValue(newValue);
return newValue;
}
}
// Usage
IMap<String, Integer> counters = hz.getMap("counters");
Integer result = counters.executeOnKey("page-views", new IncrementCounterProcessor(1));
// Execute on multiple keys
Set<String> keys = Set.of("counter1", "counter2", "counter3");
Map<String, Integer> results = counters.executeOnKeys(keys, new IncrementCounterProcessor(5));A distributed data structure where each key can be associated with multiple values.
import com.hazelcast.multimap.MultiMap;
import java.util.Collection;
public interface MultiMap<K, V> extends DistributedObject {
// Basic operations
boolean put(K key, V value);
Collection<V> get(K key);
boolean remove(Object key, Object value);
Collection<V> remove(Object key);
// Query operations
Set<K> keySet();
Collection<V> values();
Set<Entry<K, V>> entrySet();
// Bulk operations
boolean containsKey(K key);
boolean containsValue(Object value);
boolean containsEntry(K key, V value);
int size();
void clear();
// Listeners
UUID addEntryListener(EntryListener<K, V> listener, boolean includeValue);
UUID addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue);
boolean removeEntryListener(UUID registrationId);
// Locking
void lock(K key);
void unlock(K key);
boolean tryLock(K key);
boolean isLocked(K key);
// Statistics
LocalMultiMapStats getLocalMultiMapStats();
}MultiMap<String, String> categoryMap = hz.getMultiMap("categories");
// Add multiple values for same key
categoryMap.put("fruits", "apple");
categoryMap.put("fruits", "banana");
categoryMap.put("fruits", "orange");
categoryMap.put("vegetables", "carrot");
categoryMap.put("vegetables", "lettuce");
// Get all values for a key
Collection<String> fruits = categoryMap.get("fruits"); // [apple, banana, orange]
// Remove specific value
categoryMap.remove("fruits", "banana");
// Remove all values for key
Collection<String> removed = categoryMap.remove("vegetables");Eventually consistent replicated map that stores data on every cluster member.
import com.hazelcast.replicatedmap.ReplicatedMap;
public interface ReplicatedMap<K, V> extends Map<K, V>, DistributedObject {
// Standard Map operations
V put(K key, V value);
V put(K key, V value, long ttl, TimeUnit timeunit);
V get(Object key);
V remove(Object key);
// Async operations
ICompletableFuture<V> putAsync(K key, V value);
ICompletableFuture<V> putAsync(K key, V value, long ttl, TimeUnit timeunit);
ICompletableFuture<V> getAsync(K key);
ICompletableFuture<V> removeAsync(K key);
// Listeners
UUID addEntryListener(EntryListener<K, V> listener);
UUID addEntryListener(EntryListener<K, V> listener, K key);
UUID addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate);
boolean removeEntryListener(UUID registrationId);
// Query operations
Collection<V> values(Predicate<K, V> predicate);
Set<Entry<K, V>> entrySet(Predicate<K, V> predicate);
Set<K> keySet(Predicate<K, V> predicate);
void clear();
}Distributed implementation of java.util.concurrent.BlockingQueue.
import com.hazelcast.collection.IQueue;
import com.hazelcast.collection.ItemListener;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public interface IQueue<E> extends BlockingQueue<E>, DistributedObject {
// Blocking operations
boolean offer(E item);
boolean offer(E item, long timeout, TimeUnit unit) throws InterruptedException;
E poll();
E poll(long timeout, TimeUnit unit) throws InterruptedException;
E take() throws InterruptedException;
E peek();
// Capacity and size
int remainingCapacity();
boolean contains(Object o);
int drainTo(Collection<? super E> c);
int drainTo(Collection<? super E> c, int maxElements);
// Collection operations
boolean add(E e);
boolean remove(Object o);
void clear();
int size();
boolean isEmpty();
Object[] toArray();
<T> T[] toArray(T[] a);
// Iterator support
Iterator<E> iterator();
// Listeners
UUID addItemListener(ItemListener<E> listener, boolean includeValue);
boolean removeItemListener(UUID registrationId);
// Statistics
LocalQueueStats getLocalQueueStats();
}IQueue<Task> taskQueue = hz.getQueue("task-queue");
// Producer
Task task = new Task("process-order", orderId);
taskQueue.offer(task); // Non-blocking
taskQueue.put(task); // Blocking if full
// Consumer
Task nextTask = taskQueue.poll(); // Non-blocking, returns null if empty
Task taskWithTimeout = taskQueue.poll(5, TimeUnit.SECONDS); // Wait up to 5 seconds
Task blockingTask = taskQueue.take(); // Block until available
// Item listener
taskQueue.addItemListener(new ItemListener<Task>() {
@Override
public void itemAdded(ItemEvent<Task> item) {
System.out.println("Task added: " + item.getItem());
}
@Override
public void itemRemoved(ItemEvent<Task> item) {
System.out.println("Task removed: " + item.getItem());
}
}, true);Distributed implementation of java.util.List.
import com.hazelcast.collection.IList;
import java.util.List;
public interface IList<E> extends List<E>, DistributedObject {
// Standard List operations
boolean add(E e);
void add(int index, E element);
boolean addAll(Collection<? extends E> c);
boolean addAll(int index, Collection<? extends E> c);
E get(int index);
E set(int index, E element);
E remove(int index);
boolean remove(Object o);
int indexOf(Object o);
int lastIndexOf(Object o);
boolean contains(Object o);
boolean containsAll(Collection<?> c);
List<E> subList(int fromIndex, int toIndex);
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Collection operations
void clear();
int size();
boolean isEmpty();
Object[] toArray();
<T> T[] toArray(T[] a);
// Listeners
UUID addItemListener(ItemListener<E> listener, boolean includeValue);
boolean removeItemListener(UUID registrationId);
// Statistics
LocalCollectionStats getLocalCollectionStats();
}Distributed implementation of java.util.Set.
import com.hazelcast.collection.ISet;
import java.util.Set;
public interface ISet<E> extends Set<E>, DistributedObject {
// Standard Set operations
boolean add(E e);
boolean addAll(Collection<? extends E> c);
boolean remove(Object o);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
boolean contains(Object o);
boolean containsAll(Collection<?> c);
// Collection operations
void clear();
int size();
boolean isEmpty();
Object[] toArray();
<T> T[] toArray(T[] a);
Iterator<E> iterator();
// Listeners
UUID addItemListener(ItemListener<E> listener, boolean includeValue);
boolean removeItemListener(UUID registrationId);
// Statistics
LocalCollectionStats getLocalCollectionStats();
}// Distributed list
IList<String> distributedList = hz.getList("my-list");
distributedList.add("first");
distributedList.add(1, "second"); // Insert at index
String item = distributedList.get(0);
// Distributed set
ISet<String> distributedSet = hz.getSet("unique-items");
distributedSet.add("unique-value");
boolean added = distributedSet.add("unique-value"); // Returns false (already exists)
boolean contains = distributedSet.contains("unique-value");High-performance circular buffer for reliable messaging.
import com.hazelcast.ringbuffer.Ringbuffer;
import com.hazelcast.ringbuffer.ReadResultSet;
import java.util.concurrent.CompletionStage;
public interface Ringbuffer<E> extends DistributedObject {
// Write operations
long add(E item);
CompletionStage<Long> addAsync(E item, OverflowPolicy overflowPolicy);
long addAll(Collection<? extends E> collection, OverflowPolicy overflowPolicy);
CompletionStage<Long> addAllAsync(Collection<? extends E> collection, OverflowPolicy overflowPolicy);
// Read operations
E readOne(long sequence) throws InterruptedException;
CompletionStage<ReadResultSet<E>> readManyAsync(long startSequence, int minCount, int maxCount);
// Information
long headSequence();
long tailSequence();
long size();
long capacity();
long remainingCapacity();
}Distributed publish-subscribe messaging.
import com.hazelcast.topic.ITopic;
import com.hazelcast.topic.MessageListener;
import java.util.concurrent.CompletionStage;
public interface ITopic<E> extends DistributedObject {
// Publishing
void publish(E message);
CompletionStage<Void> publishAsync(E message);
// Subscription
UUID addMessageListener(MessageListener<E> listener);
boolean removeMessageListener(UUID registrationId);
// Statistics
LocalTopicStats getLocalTopicStats();
}
public interface MessageListener<E> {
void onMessage(Message<E> message);
}
public interface Message<E> {
E getMessageObject();
Member getPublishingMember();
long getPublishTime();
}// Ringbuffer usage
Ringbuffer<String> ringbuffer = hz.getRingbuffer("events");
// Producer
long sequence = ringbuffer.add("event-data");
// Consumer
String event = ringbuffer.readOne(sequence);
// Batch reading
ReadResultSet<String> resultSet = ringbuffer.readManyAsync(0, 1, 10).toCompletableFuture().get();
for (String item : resultSet) {
System.out.println("Read: " + item);
}
// Topic usage
ITopic<String> topic = hz.getTopic("notifications");
// Publisher
topic.publish("Hello subscribers!");
// Subscriber
topic.addMessageListener(message -> {
System.out.println("Received: " + message.getMessageObject());
System.out.println("From: " + message.getPublishingMember());
});Cluster-wide unique ID generator.
import com.hazelcast.flakeidgen.FlakeIdGenerator;
public interface FlakeIdGenerator extends DistributedObject {
long newId();
boolean init(long id);
}
// Usage
FlakeIdGenerator idGenerator = hz.getFlakeIdGenerator("user-ids");
long uniqueId = idGenerator.newId();HyperLogLog-based cardinality estimation.
import com.hazelcast.cardinality.CardinalityEstimator;
public interface CardinalityEstimator extends DistributedObject {
void add(Object obj);
void addAll(Collection<?> objects);
long estimate();
}
// Usage
CardinalityEstimator estimator = hz.getCardinalityEstimator("unique-visitors");
estimator.add("user123");
estimator.add("user456");
long uniqueCount = estimator.estimate();Conflict-free replicated counter.
import com.hazelcast.crdt.pncounter.PNCounter;
public interface PNCounter extends DistributedObject {
long get();
long getAndAdd(long delta);
long addAndGet(long delta);
long getAndSubtract(long delta);
long subtractAndGet(long delta);
long decrementAndGet();
long incrementAndGet();
long getAndDecrement();
long getAndIncrement();
void reset();
}
// Usage
PNCounter counter = hz.getPNCounter("global-counter");
long newValue = counter.incrementAndGet();
counter.addAndGet(10);
long currentValue = counter.get();import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.map.MapEvent;
public interface EntryListener<K, V> extends MapListener {
void entryAdded(EntryEvent<K, V> event);
void entryEvicted(EntryEvent<K, V> event);
void entryExpired(EntryEvent<K, V> event);
void entryRemoved(EntryEvent<K, V> event);
void entryUpdated(EntryEvent<K, V> event);
void mapCleared(MapEvent event);
void mapEvicted(MapEvent event);
}
// Usage example
IMap<String, User> userMap = hz.getMap("users");
userMap.addEntryListener(new EntryListener<String, User>() {
@Override
public void entryAdded(EntryEvent<String, User> event) {
System.out.println("User added: " + event.getKey() + " = " + event.getValue());
}
@Override
public void entryUpdated(EntryEvent<String, User> event) {
System.out.println("User updated: " + event.getKey());
System.out.println("Old value: " + event.getOldValue());
System.out.println("New value: " + event.getValue());
}
// ... other methods
}, true); // includeValue = trueimport com.hazelcast.core.ItemEvent;
import com.hazelcast.core.ItemListener;
public interface ItemListener<E> {
void itemAdded(ItemEvent<E> item);
void itemRemoved(ItemEvent<E> item);
}
// Usage example
IQueue<Task> taskQueue = hz.getQueue("tasks");
taskQueue.addItemListener(new ItemListener<Task>() {
@Override
public void itemAdded(ItemEvent<Task> event) {
System.out.println("Task queued: " + event.getItem());
}
@Override
public void itemRemoved(ItemEvent<Task> event) {
System.out.println("Task processed: " + event.getItem());
}
}, true);import com.hazelcast.core.DistributedObject;
public interface DistributedObject {
String getName();
String getServiceName();
void destroy();
PartitionKey getPartitionKey();
}import com.hazelcast.config.IndexConfig;
import com.hazelcast.config.IndexType;
public class IndexConfig {
public IndexConfig();
public IndexConfig(IndexType type, String... attributes);
public IndexConfig setName(String name);
public String getName();
public IndexConfig setType(IndexType type);
public IndexType getType();
public IndexConfig setAttributes(List<String> attributes);
public List<String> getAttributes();
}
public enum IndexType {
SORTED,
HASH,
BITMAP
}import com.hazelcast.map.listener.MapListener;
public interface MapListener {
// Marker interface for all map listeners
}Install with Tessl CLI
npx tessl i tessl/maven-com-hazelcast--hazelcast