0
# Core API and Instance Management
1
2
The Hazelcast Core API provides the fundamental interfaces for creating and managing Hazelcast instances, accessing distributed objects, and controlling the instance lifecycle.
3
4
## Main Entry Point
5
6
### HazelcastInstance Interface
7
8
```java { .api }
9
import com.hazelcast.core.HazelcastInstance;
10
import com.hazelcast.core.DistributedObject;
11
import com.hazelcast.config.Config;
12
import com.hazelcast.cluster.Cluster;
13
import com.hazelcast.partition.PartitionService;
14
15
public interface HazelcastInstance {
16
// Instance information
17
String getName();
18
Config getConfig();
19
20
// Distributed objects access
21
<K, V> IMap<K, V> getMap(String name);
22
<E> IQueue<E> getQueue(String name);
23
<E> IList<E> getList(String name);
24
<E> ISet<E> getSet(String name);
25
<K, V> MultiMap<K, V> getMultiMap(String name);
26
<K, V> ReplicatedMap<K, V> getReplicatedMap(String name);
27
<E> ITopic<E> getTopic(String name);
28
<E> ITopic<E> getReliableTopic(String name);
29
<E> Ringbuffer<E> getRingbuffer(String name);
30
31
// Executor services
32
IExecutorService getExecutorService(String name);
33
DurableExecutorService getDurableExecutorService(String name);
34
IScheduledExecutorService getScheduledExecutorService(String name);
35
36
// Specialized data structures
37
FlakeIdGenerator getFlakeIdGenerator(String name);
38
CardinalityEstimator getCardinalityEstimator(String name);
39
PNCounter getPNCounter(String name);
40
41
// Services
42
CPSubsystem getCPSubsystem();
43
SqlService getSql();
44
JetService getJet();
45
Cluster getCluster();
46
PartitionService getPartitionService();
47
LifecycleService getLifecycleService();
48
ClientService getClientService();
49
LoggingService getLoggingService();
50
SplitBrainProtectionService getSplitBrainProtectionService();
51
52
// Cache management
53
ICacheManager getCacheManager();
54
55
// Transaction support
56
TransactionContext newTransactionContext();
57
TransactionContext newTransactionContext(TransactionOptions options);
58
<T> T executeTransaction(TransactionalTask<T> task);
59
<T> T executeTransaction(TransactionOptions options, TransactionalTask<T> task);
60
61
// Distributed object management
62
Collection<DistributedObject> getDistributedObjects();
63
<T extends DistributedObject> T getDistributedObject(String serviceName, String name);
64
UUID addDistributedObjectListener(DistributedObjectListener distributedObjectListener);
65
boolean removeDistributedObjectListener(UUID registrationId);
66
67
// Local endpoint and context
68
Endpoint getLocalEndpoint();
69
ConcurrentMap<String, Object> getUserContext();
70
71
// XA Transaction support
72
HazelcastXAResource getXAResource();
73
74
// Lifecycle
75
void shutdown();
76
}
77
```
78
79
### Factory Methods
80
81
#### Server Instance Factory
82
83
```java { .api }
84
import com.hazelcast.core.Hazelcast;
85
import com.hazelcast.core.HazelcastInstance;
86
import com.hazelcast.config.Config;
87
import java.util.Set;
88
89
public class Hazelcast {
90
// Create new instance
91
public static HazelcastInstance newHazelcastInstance();
92
public static HazelcastInstance newHazelcastInstance(Config config);
93
94
// Get existing instances
95
public static HazelcastInstance getHazelcastInstanceByName(String instanceName);
96
public static HazelcastInstance getOrCreateHazelcastInstance(Config config);
97
public static Set<HazelcastInstance> getAllHazelcastInstances();
98
99
// For Jet jobs
100
public static HazelcastInstance bootstrappedInstance();
101
102
// Shutdown operations
103
public static void shutdownAll();
104
105
// Memory management
106
public static void setOutOfMemoryHandler(OutOfMemoryHandler outOfMemoryHandler);
107
}
108
```
109
110
#### Client Factory
111
112
```java { .api }
113
import com.hazelcast.client.HazelcastClient;
114
import com.hazelcast.client.config.ClientConfig;
115
import com.hazelcast.client.config.ClientFailoverConfig;
116
import java.util.Collection;
117
118
public class HazelcastClient {
119
// Create new client
120
public static HazelcastInstance newHazelcastClient();
121
public static HazelcastInstance newHazelcastClient(ClientConfig config);
122
123
// Failover client
124
public static HazelcastInstance newHazelcastFailoverClient();
125
public static HazelcastInstance newHazelcastFailoverClient(ClientFailoverConfig clientFailoverConfig);
126
127
// Get existing clients
128
public static HazelcastInstance getHazelcastClientByName(String instanceName);
129
public static HazelcastInstance getOrCreateHazelcastClient(ClientConfig config);
130
public static Collection<HazelcastInstance> getAllHazelcastClients();
131
132
// Shutdown operations
133
public static void shutdownAll();
134
public static void shutdown(HazelcastInstance instance);
135
136
// Memory management
137
public static void setOutOfMemoryHandler(OutOfMemoryHandler outOfMemoryHandler);
138
}
139
```
140
141
## Instance Creation Examples
142
143
### Basic Server Instance
144
145
```java { .api }
146
import com.hazelcast.core.Hazelcast;
147
import com.hazelcast.core.HazelcastInstance;
148
149
// Default configuration
150
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
151
152
// Named instance
153
Config config = new Config();
154
config.setInstanceName("my-hazelcast-instance");
155
HazelcastInstance namedHz = Hazelcast.newHazelcastInstance(config);
156
157
// Get existing instance
158
HazelcastInstance existing = Hazelcast.getHazelcastInstanceByName("my-hazelcast-instance");
159
```
160
161
### Basic Client Instance
162
163
```java { .api }
164
import com.hazelcast.client.HazelcastClient;
165
import com.hazelcast.client.config.ClientConfig;
166
167
// Default client configuration
168
HazelcastInstance client = HazelcastClient.newHazelcastClient();
169
170
// Custom client configuration
171
ClientConfig clientConfig = new ClientConfig();
172
clientConfig.setInstanceName("my-client");
173
clientConfig.getNetworkConfig().addAddress("192.168.1.100:5701", "192.168.1.101:5701");
174
HazelcastInstance customClient = HazelcastClient.newHazelcastClient(clientConfig);
175
```
176
177
### Programmatic Configuration
178
179
```java { .api }
180
import com.hazelcast.config.Config;
181
import com.hazelcast.config.MapConfig;
182
import com.hazelcast.config.NetworkConfig;
183
184
Config config = new Config();
185
186
// Instance settings
187
config.setInstanceName("production-cluster");
188
config.setClusterName("prod");
189
190
// Map configuration
191
MapConfig mapConfig = new MapConfig("user-sessions");
192
mapConfig.setBackupCount(2);
193
mapConfig.setTimeToLiveSeconds(1800); // 30 minutes
194
config.addMapConfig(mapConfig);
195
196
// Network configuration
197
NetworkConfig networkConfig = config.getNetworkConfig();
198
networkConfig.setPort(5701);
199
networkConfig.setPortAutoIncrement(true);
200
networkConfig.setPortCount(20);
201
202
HazelcastInstance hz = Hazelcast.newHazelcastInstance(config);
203
```
204
205
## Distributed Object Management
206
207
### Base Interface
208
209
```java { .api }
210
import com.hazelcast.core.DistributedObject;
211
212
public interface DistributedObject {
213
String getName();
214
String getServiceName();
215
String getPartitionKey();
216
void destroy();
217
}
218
```
219
220
### Accessing Distributed Objects
221
222
```java { .api }
223
// Maps
224
IMap<String, User> userMap = hz.getMap("users");
225
IMap<Long, Order> orderMap = hz.getMap("orders");
226
227
// Collections
228
IQueue<Task> taskQueue = hz.getQueue("tasks");
229
IList<String> messages = hz.getList("messages");
230
ISet<String> uniqueItems = hz.getSet("unique-items");
231
232
// Topics
233
ITopic<String> notifications = hz.getTopic("notifications");
234
ITopic<Event> events = hz.getReliableTopic("events");
235
236
// Specialized structures
237
FlakeIdGenerator idGen = hz.getFlakeIdGenerator("user-ids");
238
CardinalityEstimator estimator = hz.getCardinalityEstimator("page-views");
239
PNCounter counter = hz.getPNCounter("global-counter");
240
```
241
242
## Lifecycle Management
243
244
### LifecycleService Interface
245
246
```java { .api }
247
import com.hazelcast.core.LifecycleService;
248
import com.hazelcast.core.LifecycleListener;
249
import com.hazelcast.core.LifecycleEvent;
250
import java.util.UUID;
251
252
public interface LifecycleService {
253
boolean isRunning();
254
UUID addLifecycleListener(LifecycleListener lifecycleListener);
255
boolean removeLifecycleListener(UUID registrationId);
256
void shutdown();
257
void terminate();
258
}
259
```
260
261
### LifecycleListener Interface
262
263
```java { .api }
264
public interface LifecycleListener {
265
void stateChanged(LifecycleEvent event);
266
}
267
268
public class LifecycleEvent {
269
public enum LifecycleState {
270
STARTING, STARTED, SHUTTING_DOWN, SHUTDOWN, MERGING, MERGED,
271
CLIENT_CONNECTED, CLIENT_DISCONNECTED
272
}
273
274
public LifecycleState getState();
275
public HazelcastInstance getSource();
276
}
277
```
278
279
### Lifecycle Management Example
280
281
```java { .api }
282
LifecycleService lifecycle = hz.getLifecycleService();
283
284
// Add lifecycle listener
285
UUID listenerId = lifecycle.addLifecycleListener(new LifecycleListener() {
286
@Override
287
public void stateChanged(LifecycleEvent event) {
288
System.out.println("Lifecycle state changed: " + event.getState());
289
290
switch (event.getState()) {
291
case STARTED:
292
System.out.println("Instance started successfully");
293
break;
294
case SHUTTING_DOWN:
295
System.out.println("Instance is shutting down");
296
break;
297
case SHUTDOWN:
298
System.out.println("Instance has shut down");
299
break;
300
}
301
}
302
});
303
304
// Check if running
305
if (lifecycle.isRunning()) {
306
System.out.println("Instance is running");
307
}
308
309
// Graceful shutdown
310
lifecycle.shutdown();
311
312
// Remove listener
313
lifecycle.removeLifecycleListener(listenerId);
314
```
315
316
## Exception Handling
317
318
### Core Exceptions
319
320
```java { .api }
321
import com.hazelcast.core.HazelcastException;
322
import com.hazelcast.core.HazelcastInstanceNotActiveException;
323
import com.hazelcast.core.HazelcastOverloadException;
324
import com.hazelcast.core.OperationTimeoutException;
325
import com.hazelcast.core.MemberLeftException;
326
import com.hazelcast.core.ConsistencyLostException;
327
328
// Base exception
329
public class HazelcastException extends RuntimeException {
330
public HazelcastException(String message);
331
public HazelcastException(String message, Throwable cause);
332
}
333
334
// Specific exceptions
335
public class HazelcastInstanceNotActiveException extends IllegalStateException {}
336
public class HazelcastOverloadException extends HazelcastException {}
337
public class OperationTimeoutException extends HazelcastException {}
338
public class MemberLeftException extends HazelcastException {}
339
public class ConsistencyLostException extends HazelcastException {}
340
```
341
342
### Exception Handling Example
343
344
```java { .api }
345
try {
346
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
347
IMap<String, String> map = hz.getMap("test");
348
349
String result = map.get("key");
350
351
} catch (HazelcastInstanceNotActiveException e) {
352
System.err.println("Instance is not active: " + e.getMessage());
353
} catch (OperationTimeoutException e) {
354
System.err.println("Operation timed out: " + e.getMessage());
355
} catch (HazelcastException e) {
356
System.err.println("Hazelcast operation failed: " + e.getMessage());
357
}
358
```
359
360
## Utility Interfaces
361
362
### Execution Callbacks
363
364
```java { .api }
365
import com.hazelcast.core.ExecutionCallback;
366
import com.hazelcast.core.MultiExecutionCallback;
367
import java.util.Map;
368
369
public interface ExecutionCallback<V> {
370
void onResponse(V response);
371
void onFailure(Throwable t);
372
}
373
374
public interface MultiExecutionCallback {
375
void onResponse(Member member, Object value);
376
void onComplete(Map<Member, Object> values);
377
}
378
```
379
380
### Function Interface
381
382
```java { .api }
383
import com.hazelcast.core.IFunction;
384
import java.io.Serializable;
385
386
public interface IFunction<E, R> extends Serializable {
387
R apply(E input);
388
}
389
```
390
391
### Service Interfaces
392
393
#### Client Service
394
395
```java { .api }
396
import com.hazelcast.client.ClientService;
397
import com.hazelcast.client.Client;
398
import java.util.Collection;
399
400
public interface ClientService {
401
Collection<Client> getConnectedClients();
402
void addClientListener(ClientListener clientListener);
403
void removeClientListener(ClientListener clientListener);
404
}
405
406
public interface Client extends Endpoint {
407
String getUuid();
408
String getName();
409
String getClientType();
410
InetSocketAddress getSocketAddress();
411
}
412
413
public interface ClientListener {
414
void clientConnected(Client client);
415
void clientDisconnected(Client client);
416
}
417
```
418
419
#### Logging Service
420
421
```java { .api }
422
import com.hazelcast.logging.LoggingService;
423
import com.hazelcast.logging.LogListener;
424
import com.hazelcast.logging.LogEvent;
425
426
public interface LoggingService {
427
void addLogListener(Level level, LogListener logListener);
428
void removeLogListener(LogListener logListener);
429
}
430
431
public interface LogListener {
432
void log(LogEvent logEvent);
433
}
434
435
public class LogEvent {
436
public LogRecord getLogRecord();
437
public Member getMember();
438
}
439
```
440
441
#### Split Brain Protection Service
442
443
```java { .api }
444
import com.hazelcast.splitbrainprotection.SplitBrainProtectionService;
445
import com.hazelcast.splitbrainprotection.SplitBrainProtection;
446
447
public interface SplitBrainProtectionService {
448
SplitBrainProtection getSplitBrainProtection(String splitBrainProtectionName);
449
}
450
451
public interface SplitBrainProtection {
452
String getName();
453
boolean isPresent();
454
int getSize();
455
}
456
```
457
458
#### Transaction Support Types
459
460
```java { .api }
461
import com.hazelcast.transaction.TransactionContext;
462
import com.hazelcast.transaction.TransactionOptions;
463
import com.hazelcast.transaction.TransactionalTask;
464
import com.hazelcast.transaction.HazelcastXAResource;
465
466
public interface TransactionContext {
467
void beginTransaction();
468
void commitTransaction();
469
void rollbackTransaction();
470
String getTxnId();
471
TransactionOptions getTransactionOptions();
472
473
// Transactional data structures
474
<K, V> TransactionalMap<K, V> getMap(String name);
475
<E> TransactionalQueue<E> getQueue(String name);
476
<E> TransactionalList<E> getList(String name);
477
<E> TransactionalSet<E> getSet(String name);
478
<K, V> TransactionalMultiMap<K, V> getMultiMap(String name);
479
}
480
481
public class TransactionOptions {
482
public static final TransactionOptions DEFAULT = new TransactionOptions();
483
484
public TransactionOptions setTimeout(long timeout, TimeUnit timeUnit);
485
public TransactionOptions setTransactionType(TransactionType transactionType);
486
public long getTimeoutMillis();
487
public TransactionType getTransactionType();
488
}
489
490
public interface TransactionalTask<T> extends Serializable {
491
T execute(TransactionContext context) throws TransactionException;
492
}
493
494
public interface HazelcastXAResource extends XAResource {
495
void clearContext();
496
TransactionContext getTransactionContext();
497
}
498
```
499
500
#### Distributed Object Support
501
502
```java { .api }
503
import com.hazelcast.core.DistributedObjectListener;
504
import com.hazelcast.core.DistributedObjectEvent;
505
import com.hazelcast.cluster.Endpoint;
506
507
public interface DistributedObjectListener extends EventListener {
508
void distributedObjectCreated(DistributedObjectEvent event);
509
void distributedObjectDestroyed(DistributedObjectEvent event);
510
}
511
512
public class DistributedObjectEvent {
513
public enum EventType { CREATED, DESTROYED }
514
515
public String getObjectName();
516
public String getServiceName();
517
public EventType getEventType();
518
public Member getMember();
519
}
520
521
public interface Endpoint {
522
UUID getUuid();
523
InetSocketAddress getSocketAddress();
524
Map<String, String> getAttributes();
525
}
526
```
527
528
## Best Practices
529
530
### Instance Management
531
532
```java { .api }
533
// Use try-with-resources pattern for automatic cleanup
534
public class HazelcastManager implements AutoCloseable {
535
private final HazelcastInstance hazelcast;
536
537
public HazelcastManager(Config config) {
538
this.hazelcast = Hazelcast.newHazelcastInstance(config);
539
}
540
541
public HazelcastInstance getInstance() {
542
return hazelcast;
543
}
544
545
@Override
546
public void close() {
547
if (hazelcast != null && hazelcast.getLifecycleService().isRunning()) {
548
hazelcast.shutdown();
549
}
550
}
551
}
552
553
// Usage
554
try (HazelcastManager manager = new HazelcastManager(config)) {
555
HazelcastInstance hz = manager.getInstance();
556
// Use hz for operations
557
}
558
```
559
560
### Error Recovery
561
562
```java { .api }
563
public HazelcastInstance createResilientInstance(Config config) {
564
int maxRetries = 3;
565
int retryDelay = 1000; // ms
566
567
for (int i = 0; i < maxRetries; i++) {
568
try {
569
return Hazelcast.newHazelcastInstance(config);
570
} catch (Exception e) {
571
if (i == maxRetries - 1) {
572
throw new RuntimeException("Failed to create Hazelcast instance after " + maxRetries + " attempts", e);
573
}
574
575
try {
576
Thread.sleep(retryDelay);
577
} catch (InterruptedException ie) {
578
Thread.currentThread().interrupt();
579
throw new RuntimeException("Interrupted while retrying", ie);
580
}
581
}
582
}
583
584
throw new RuntimeException("Should not reach here");
585
}
586
```