0
# Core API
1
2
Core Vert.x API including the main entry points, verticle management, asynchronous programming primitives, and execution context handling.
3
4
## Capabilities
5
6
### Vertx Instance Creation
7
8
Main factory methods for creating Vert.x instances with various configurations.
9
10
```java { .api }
11
/**
12
* Create a Vert.x instance with default options
13
* @return Vertx instance
14
*/
15
static Vertx vertx();
16
17
/**
18
* Create a Vert.x instance with custom options
19
* @param options Configuration options for the Vertx instance
20
* @return Vertx instance
21
*/
22
static Vertx vertx(VertxOptions options);
23
24
/**
25
* Create a clustered Vert.x instance asynchronously
26
* @param options Configuration options including cluster settings
27
* @return Future that completes with clustered Vertx instance
28
*/
29
static Future<Vertx> clusteredVertx(VertxOptions options);
30
31
/**
32
* Create a Vert.x builder for more complex configuration
33
* @return VertxBuilder for fluent configuration
34
*/
35
static VertxBuilder builder();
36
37
interface VertxBuilder {
38
VertxBuilder with(VertxOptions options);
39
Vertx build();
40
}
41
```
42
43
### Verticle Deployment and Management
44
45
Deploy and manage verticles - the basic deployment units in Vert.x applications.
46
47
```java { .api }
48
/**
49
* Deploy a verticle instance
50
* @param verticle The verticle instance to deploy
51
* @return Future that completes with deployment ID
52
*/
53
Future<String> deployVerticle(Verticle verticle);
54
55
/**
56
* Deploy a verticle instance with options
57
* @param verticle The verticle instance to deploy
58
* @param options Deployment configuration
59
* @return Future that completes with deployment ID
60
*/
61
Future<String> deployVerticle(Verticle verticle, DeploymentOptions options);
62
63
/**
64
* Deploy a verticle by name/class
65
* @param name Verticle name or class name
66
* @return Future that completes with deployment ID
67
*/
68
Future<String> deployVerticle(String name);
69
70
/**
71
* Deploy a verticle by name with options
72
* @param name Verticle name or class name
73
* @param options Deployment configuration
74
* @return Future that completes with deployment ID
75
*/
76
Future<String> deployVerticle(String name, DeploymentOptions options);
77
78
/**
79
* Undeploy a verticle
80
* @param deploymentID The deployment ID returned from deployVerticle
81
* @return Future that completes when undeployment is done
82
*/
83
Future<Void> undeploy(String deploymentID);
84
85
/**
86
* Get all deployment IDs
87
* @return Set of deployment IDs
88
*/
89
Set<String> deploymentIDs();
90
91
/**
92
* Check if verticle is deployed
93
* @param deploymentID The deployment ID to check
94
* @return true if deployed
95
*/
96
boolean isDeployed(String deploymentID);
97
```
98
99
### Future and Promise Operations
100
101
Asynchronous programming primitives for composing and handling asynchronous operations.
102
103
```java { .api }
104
/**
105
* Core Future interface for asynchronous operations
106
*/
107
interface Future<T> extends AsyncResult<T> {
108
/**
109
* Add a handler to be called when the future succeeds
110
* @param handler Handler to call with the result
111
* @return this Future for chaining
112
*/
113
Future<T> onSuccess(Handler<T> handler);
114
115
/**
116
* Add a handler to be called when the future fails
117
* @param handler Handler to call with the failure cause
118
* @return this Future for chaining
119
*/
120
Future<T> onFailure(Handler<Throwable> handler);
121
122
/**
123
* Add a handler to be called when the future completes (success or failure)
124
* @param handler Handler to call with the AsyncResult
125
* @return this Future for chaining
126
*/
127
Future<T> onComplete(Handler<AsyncResult<T>> handler);
128
129
/**
130
* Compose this future with another future-returning function
131
* @param successMapper Function to apply to successful result
132
* @return New Future with composed result
133
*/
134
<U> Future<U> compose(Function<T, Future<U>> successMapper);
135
136
/**
137
* Transform the result of this future
138
* @param mapper Function to transform the result
139
* @return New Future with transformed result
140
*/
141
<U> Future<U> map(Function<T, U> mapper);
142
143
/**
144
* Recover from failure by returning another future
145
* @param mapper Function to handle failure and return recovery future
146
* @return New Future with recovery handling
147
*/
148
Future<T> recover(Function<Throwable, Future<T>> mapper);
149
150
/**
151
* Transform failure to success with a default value
152
* @param value Default value to use on failure
153
* @return New Future that succeeds with value on failure
154
*/
155
Future<T> otherwise(T value);
156
157
/**
158
* Apply a function regardless of success/failure
159
* @param mapper Function to apply to the result
160
* @return New Future with transformation applied
161
*/
162
<U> Future<U> eventually(Function<Void, Future<U>> mapper);
163
164
// Static factory methods
165
static <T> Future<T> succeededFuture();
166
static <T> Future<T> succeededFuture(T result);
167
static <T> Future<T> failedFuture(Throwable t);
168
static <T> Future<T> failedFuture(String message);
169
static <T> Future<T> future();
170
static <T> Future<T> future(Promise<T> promise);
171
}
172
173
/**
174
* Promise interface for completing futures
175
*/
176
interface Promise<T> extends Handler<AsyncResult<T>> {
177
/**
178
* Complete the promise with a result
179
* @param result The result
180
*/
181
void complete(T result);
182
183
/**
184
* Complete the promise with success (no result)
185
*/
186
void complete();
187
188
/**
189
* Fail the promise with a cause
190
* @param cause The failure cause
191
*/
192
void fail(Throwable cause);
193
194
/**
195
* Fail the promise with a message
196
* @param message The failure message
197
*/
198
void fail(String message);
199
200
/**
201
* Get the future associated with this promise
202
* @return The future
203
*/
204
Future<T> future();
205
206
/**
207
* Try to complete the promise (returns false if already completed)
208
* @param result The result
209
* @return true if completed, false if already completed
210
*/
211
boolean tryComplete(T result);
212
213
/**
214
* Try to fail the promise (returns false if already completed)
215
* @param cause The failure cause
216
* @return true if failed, false if already completed
217
*/
218
boolean tryFail(Throwable cause);
219
220
// Static factory
221
static <T> Promise<T> promise();
222
}
223
```
224
225
### Composite Future Operations
226
227
Operations for handling multiple futures together.
228
229
```java { .api }
230
/**
231
* Composite future for handling multiple futures
232
*/
233
interface CompositeFuture extends Future<CompositeFuture> {
234
/**
235
* Check if all futures succeeded
236
* @return true if all succeeded
237
*/
238
boolean isComplete();
239
240
/**
241
* Get the cause at a specific index
242
* @param index The index
243
* @return The cause or null
244
*/
245
Throwable cause(int index);
246
247
/**
248
* Check if future at index succeeded
249
* @param index The index
250
* @return true if succeeded
251
*/
252
boolean succeeded(int index);
253
254
/**
255
* Check if future at index failed
256
* @param index The index
257
* @return true if failed
258
*/
259
boolean failed(int index);
260
261
/**
262
* Get result at specific index
263
* @param index The index
264
* @return The result
265
*/
266
<T> T resultAt(int index);
267
268
/**
269
* Get all results as list
270
* @return List of results
271
*/
272
<T> List<T> list();
273
274
// Static factory methods
275
static CompositeFuture all(List<Future> futures);
276
static CompositeFuture all(Future<?>... futures);
277
static CompositeFuture any(List<Future> futures);
278
static CompositeFuture any(Future<?>... futures);
279
static CompositeFuture join(List<Future> futures);
280
static CompositeFuture join(Future<?>... futures);
281
}
282
```
283
284
### Context and Execution
285
286
Execution context management and thread-safe operations.
287
288
```java { .api }
289
/**
290
* Get the current context if running on a Vert.x thread
291
* @return Current context or null if not on Vert.x thread
292
*/
293
static Context currentContext();
294
295
/**
296
* Get or create a context for the current thread
297
* @return Context instance (current context or a new one)
298
*/
299
Context getOrCreateContext();
300
301
/**
302
* Execution context for handlers and operations
303
*/
304
interface Context {
305
/**
306
* Run code on this context
307
* @param action The action to run
308
*/
309
void runOnContext(Handler<Void> action);
310
311
/**
312
* Execute blocking code on worker thread
313
* @param blockingCodeHandler Handler containing blocking code
314
* @param resultHandler Handler to receive the result
315
*/
316
<T> void executeBlocking(Handler<Promise<T>> blockingCodeHandler, Handler<AsyncResult<T>> resultHandler);
317
318
/**
319
* Execute blocking code on worker thread with options
320
* @param blockingCodeHandler Handler containing blocking code
321
* @param ordered Whether to maintain order
322
* @param resultHandler Handler to receive the result
323
*/
324
<T> void executeBlocking(Handler<Promise<T>> blockingCodeHandler, boolean ordered, Handler<AsyncResult<T>> resultHandler);
325
326
/**
327
* Check if running on event loop context
328
* @return true if on event loop
329
*/
330
boolean isEventLoopContext();
331
332
/**
333
* Check if running on worker context
334
* @return true if on worker thread
335
*/
336
boolean isWorkerContext();
337
338
/**
339
* Check if running on multi-threaded worker context
340
* @return true if on multi-threaded worker
341
*/
342
boolean isMultiThreadedWorkerContext();
343
344
/**
345
* Put data in context-local storage
346
* @param key The key
347
* @param value The value
348
*/
349
void put(String key, Object value);
350
351
/**
352
* Get data from context-local storage
353
* @param key The key
354
* @return The value
355
*/
356
<T> T get(String key);
357
358
/**
359
* Remove data from context-local storage
360
* @param key The key
361
* @return true if removed
362
*/
363
boolean remove(String key);
364
365
/**
366
* Get verticle configuration
367
* @return Configuration JsonObject
368
*/
369
JsonObject config();
370
371
// Static utilities
372
static boolean isOnEventLoopThread();
373
static boolean isOnWorkerThread();
374
static boolean isOnVertxThread();
375
}
376
```
377
378
### Timer Operations
379
380
Timer and periodic task scheduling.
381
382
```java { .api }
383
/**
384
* Create a one-shot timer (modern approach)
385
* @param delay Delay in milliseconds
386
* @return Timer instance
387
*/
388
Timer timer(long delay);
389
390
/**
391
* Create a one-shot timer with time unit
392
* @param delay Delay amount
393
* @param unit Time unit for delay
394
* @return Timer instance
395
*/
396
Timer timer(long delay, TimeUnit unit);
397
398
/**
399
* Set a one-shot timer (legacy)
400
* @param delay Delay in milliseconds
401
* @param handler Handler to call when timer fires
402
* @return Timer ID for cancellation
403
*/
404
long setTimer(long delay, Handler<Long> handler);
405
406
/**
407
* Set a periodic timer
408
* @param delay Delay between executions in milliseconds
409
* @param handler Handler to call on each execution
410
* @return Timer ID for cancellation
411
*/
412
long setPeriodic(long delay, Handler<Long> handler);
413
414
/**
415
* Set a periodic timer with initial delay
416
* @param initialDelay Initial delay before first execution
417
* @param delay Delay between subsequent executions
418
* @param handler Handler to call on each execution
419
* @return Timer ID for cancellation
420
*/
421
long setPeriodic(long initialDelay, long delay, Handler<Long> handler);
422
423
/**
424
* Cancel a timer
425
* @param id Timer ID returned from setTimer or setPeriodic
426
* @return true if cancelled
427
*/
428
boolean cancelTimer(long id);
429
430
/**
431
* Timer interface for advanced timer operations
432
*/
433
interface Timer {
434
/**
435
* Cancel this timer
436
* @return Future that completes when cancelled
437
*/
438
Future<Void> cancel();
439
}
440
```
441
442
### Verticle Interface and Base Class
443
444
Base interfaces and classes for creating verticles.
445
446
```java { .api }
447
/**
448
* Basic verticle interface
449
*/
450
interface Verticle {
451
/**
452
* Get the Vertx instance
453
* @return The Vertx instance
454
*/
455
Vertx getVertx();
456
457
/**
458
* Initialize the verticle
459
* @param vertx The Vertx instance
460
* @param context The context
461
*/
462
void init(Vertx vertx, Context context);
463
464
/**
465
* Start the verticle
466
* @return Future that completes when started
467
*/
468
Future<Void> start();
469
470
/**
471
* Stop the verticle
472
* @return Future that completes when stopped
473
*/
474
Future<Void> stop();
475
}
476
477
/**
478
* Abstract base class for verticles
479
*/
480
abstract class AbstractVerticle implements Verticle {
481
protected Vertx vertx;
482
protected Context context;
483
484
/**
485
* Start the verticle (default implementation does nothing)
486
* @return Succeeded future
487
*/
488
public Future<Void> start() {
489
return Future.succeededFuture();
490
}
491
492
/**
493
* Stop the verticle (default implementation does nothing)
494
* @return Succeeded future
495
*/
496
public Future<Void> stop() {
497
return Future.succeededFuture();
498
}
499
}
500
```
501
502
### Worker Executors
503
504
Custom worker thread pools for blocking operations.
505
506
```java { .api }
507
/**
508
* Create a named worker executor
509
* @param name Name of the worker pool
510
* @return WorkerExecutor instance
511
*/
512
WorkerExecutor createSharedWorkerExecutor(String name);
513
514
/**
515
* Create a named worker executor with pool size
516
* @param name Name of the worker pool
517
* @param poolSize Size of the worker pool
518
* @return WorkerExecutor instance
519
*/
520
WorkerExecutor createSharedWorkerExecutor(String name, int poolSize);
521
522
/**
523
* Worker executor for custom blocking operations
524
*/
525
interface WorkerExecutor extends Measured, Closeable {
526
/**
527
* Execute blocking code on worker thread
528
* @param blockingCodeHandler Handler containing blocking code
529
* @param resultHandler Handler to receive the result
530
*/
531
<T> void executeBlocking(Handler<Promise<T>> blockingCodeHandler, Handler<AsyncResult<T>> resultHandler);
532
533
/**
534
* Execute blocking code with ordering control
535
* @param blockingCodeHandler Handler containing blocking code
536
* @param ordered Whether to maintain order
537
* @param resultHandler Handler to receive the result
538
*/
539
<T> void executeBlocking(Handler<Promise<T>> blockingCodeHandler, boolean ordered, Handler<AsyncResult<T>> resultHandler);
540
541
/**
542
* Close the worker executor
543
* @return Future that completes when closed
544
*/
545
Future<Void> close();
546
}
547
```
548
549
### Instance Management and Configuration
550
551
Vertx instance lifecycle management, exception handling, and native transport information.
552
553
```java { .api }
554
/**
555
* Close the Vertx instance
556
* @return Future that completes when closed
557
*/
558
Future<Void> close();
559
560
/**
561
* Set a default exception handler for the Vertx instance
562
* @param handler Exception handler or null to unset
563
* @return this Vertx instance
564
*/
565
Vertx exceptionHandler(Handler<Throwable> handler);
566
567
/**
568
* Get the current exception handler
569
* @return Current exception handler or null if none set
570
*/
571
Handler<Throwable> exceptionHandler();
572
573
/**
574
* Check if native transport is enabled
575
* @return true if native transport is available and enabled
576
*/
577
boolean isNativeTransportEnabled();
578
579
/**
580
* Get the cause why native transport is not available (if applicable)
581
* @return Throwable explaining why native transport is unavailable, or null if available
582
*/
583
Throwable unavailableNativeTransportCause();
584
585
/**
586
* Check if this Vertx instance is clustered
587
* @return true if clustered
588
*/
589
boolean isClustered();
590
```
591
592
## Types
593
594
```java { .api }
595
/**
596
* Configuration options for Vertx instance
597
*/
598
class VertxOptions {
599
VertxOptions setEventLoopPoolSize(int eventLoopPoolSize);
600
VertxOptions setWorkerPoolSize(int workerPoolSize);
601
VertxOptions setInternalBlockingPoolSize(int internalBlockingPoolSize);
602
VertxOptions setBlockedThreadCheckInterval(long blockedThreadCheckInterval);
603
VertxOptions setMaxEventLoopExecuteTime(long maxEventLoopExecuteTime);
604
VertxOptions setMaxWorkerExecuteTime(long maxWorkerExecuteTime);
605
VertxOptions setWarningExceptionTime(long warningExceptionTime);
606
VertxOptions setHAEnabled(boolean haEnabled);
607
VertxOptions setHAGroup(String haGroup);
608
VertxOptions setQuorumSize(int quorumSize);
609
VertxOptions setFileResolverCachingEnabled(boolean fileResolverCachingEnabled);
610
VertxOptions setMetricsOptions(MetricsOptions metricsOptions);
611
VertxOptions setTracingOptions(TracingOptions tracingOptions);
612
}
613
614
/**
615
* Configuration options for verticle deployment
616
*/
617
class DeploymentOptions {
618
DeploymentOptions setConfig(JsonObject config);
619
DeploymentOptions setWorker(boolean worker);
620
DeploymentOptions setInstances(int instances);
621
DeploymentOptions setIsolationGroup(String isolationGroup);
622
DeploymentOptions setIsolatedClasses(List<String> isolatedClasses);
623
DeploymentOptions setExtraClasspath(List<String> extraClasspath);
624
DeploymentOptions setThreadingModel(ThreadingModel threadingModel);
625
DeploymentOptions setHa(boolean ha);
626
DeploymentOptions setRedeploy(boolean redeploy);
627
DeploymentOptions setWorkerPoolName(String workerPoolName);
628
DeploymentOptions setWorkerPoolSize(int workerPoolSize);
629
DeploymentOptions setMaxWorkerExecuteTime(long maxWorkerExecuteTime);
630
}
631
632
/**
633
* Threading models for verticle execution
634
*/
635
enum ThreadingModel {
636
EVENT_LOOP, // Execute on event loop thread (default)
637
WORKER, // Execute on worker thread
638
VIRTUAL_THREAD // Execute on virtual thread (Java 19+)
639
}
640
641
/**
642
* Generic handler interface
643
*/
644
@FunctionalInterface
645
interface Handler<E> {
646
void handle(E event);
647
}
648
649
/**
650
* Result of asynchronous operation
651
*/
652
interface AsyncResult<T> {
653
T result();
654
Throwable cause();
655
boolean succeeded();
656
boolean failed();
657
<U> AsyncResult<U> map(Function<T, U> mapper);
658
<U> AsyncResult<U> map(U value);
659
AsyncResult<T> otherwise(Function<Throwable, T> mapper);
660
AsyncResult<T> otherwise(T value);
661
<U> AsyncResult<U> otherwiseEmpty();
662
}
663
664
/**
665
* Base exception for Vert.x operations
666
*/
667
class VertxException extends RuntimeException {
668
public VertxException(String message);
669
public VertxException(String message, Throwable cause);
670
public VertxException(Throwable cause);
671
}
672
```
673
674
## Usage Examples
675
676
**Basic Verticle with Timers:**
677
678
```java
679
import io.vertx.core.AbstractVerticle;
680
import io.vertx.core.Future;
681
682
public class TimerExample extends AbstractVerticle {
683
684
@Override
685
public Future<Void> start() {
686
// Set a one-shot timer
687
vertx.setTimer(1000, id -> {
688
System.out.println("Timer fired!");
689
});
690
691
// Set a periodic timer
692
long periodicId = vertx.setPeriodic(2000, id -> {
693
System.out.println("Periodic timer: " + id);
694
});
695
696
// Cancel after 10 seconds
697
vertx.setTimer(10000, id -> {
698
vertx.cancelTimer(periodicId);
699
System.out.println("Periodic timer cancelled");
700
});
701
702
return Future.succeededFuture();
703
}
704
}
705
```
706
707
**Future Composition:**
708
709
```java
710
Future<String> future1 = getUserName(userId);
711
Future<String> future2 = getUserEmail(userId);
712
713
CompositeFuture.all(future1, future2)
714
.compose(composite -> {
715
String name = composite.resultAt(0);
716
String email = composite.resultAt(1);
717
return saveUserProfile(name, email);
718
})
719
.onSuccess(profile -> System.out.println("Profile saved: " + profile))
720
.onFailure(err -> System.err.println("Failed: " + err.getMessage()));
721
```
722
723
**Blocking Code Execution:**
724
725
```java
726
vertx.executeBlocking(promise -> {
727
// This runs on worker thread
728
try {
729
String result = someBlockingOperation();
730
promise.complete(result);
731
} catch (Exception e) {
732
promise.fail(e);
733
}
734
}, result -> {
735
// This runs on event loop
736
if (result.succeeded()) {
737
System.out.println("Result: " + result.result());
738
} else {
739
System.err.println("Failed: " + result.cause().getMessage());
740
}
741
});
742
```