0
# Native Bridge
1
2
Communication APIs for bridging between different runtime environments, enabling seamless data marshalling and method calls between Native Image and HotSpot VM contexts.
3
4
## Capabilities
5
6
### Bridge Generation
7
8
Annotation-based automatic generation of bridge code for cross-runtime communication.
9
10
```java { .api }
11
/**
12
* Generate bridge from HotSpot to Native Image
13
*/
14
@Target(ElementType.TYPE)
15
@Retention(RetentionPolicy.RUNTIME)
16
public @interface GenerateHotSpotToNativeBridge {
17
/** Target native interface */
18
Class<?> value();
19
20
/** Bridge name (defaults to interface name) */
21
String name() default "";
22
23
/** Whether to include debug information */
24
boolean debug() default false;
25
26
/** Custom marshaller configuration */
27
Class<? extends MarshallerConfig> marshallerConfig() default DefaultMarshallerConfig.class;
28
}
29
30
/**
31
* Generate bridge between native contexts
32
*/
33
@Target(ElementType.TYPE)
34
@Retention(RetentionPolicy.RUNTIME)
35
public @interface GenerateNativeToNativeBridge {
36
/** Target native interface */
37
Class<?> value();
38
39
/** Bridge name (defaults to interface name) */
40
String name() default "";
41
42
/** Include performance monitoring */
43
boolean monitoring() default false;
44
}
45
```
46
47
**Usage Examples:**
48
49
```java
50
import org.graalvm.nativebridge.*;
51
52
// Define interface for bridging
53
public interface DataProcessor {
54
String processData(byte[] input, ProcessingOptions options);
55
int getVersion();
56
}
57
58
// Generate HotSpot to Native bridge
59
@GenerateHotSpotToNativeBridge(DataProcessor.class)
60
public class DataProcessorBridge {
61
// Implementation generated automatically
62
}
63
64
// Generate Native to Native bridge
65
@GenerateNativeToNativeBridge(DataProcessor.class)
66
public class FastDataProcessorBridge {
67
// High-performance native-only bridge
68
}
69
```
70
71
### Object Marshalling
72
73
Comprehensive marshalling system for converting objects between different runtime representations.
74
75
```java { .api }
76
/**
77
* Base interface for custom object marshalling between runtimes
78
*/
79
public interface BinaryMarshaller<T> {
80
/** Convert object to binary representation */
81
byte[] marshal(T object);
82
83
/** Convert binary representation back to object */
84
T unmarshal(byte[] data);
85
86
/** Get marshalled data size estimate */
87
int estimateSize(T object);
88
89
/** Check if object can be marshalled */
90
boolean canMarshal(T object);
91
}
92
93
/**
94
* Specialized marshaller for string objects with encoding support
95
*/
96
public interface StringMarshaller extends BinaryMarshaller<String> {
97
/** Convert string with specific encoding */
98
byte[] marshal(String string, Charset encoding);
99
100
/** Convert with encoding detection */
101
String unmarshal(byte[] data, Charset encoding);
102
103
/** Get supported encodings */
104
Set<Charset> getSupportedEncodings();
105
}
106
107
/**
108
* Marshaller that handles null values gracefully
109
*/
110
public interface NullableBinaryMarshaller<T> extends BinaryMarshaller<T> {
111
/** Marshal nullable object */
112
byte[] marshalNullable(T object);
113
114
/** Unmarshal potentially null object */
115
T unmarshalNullable(byte[] data);
116
117
/** Check if data represents null */
118
boolean isNull(byte[] data);
119
}
120
```
121
122
**Usage Examples:**
123
124
```java
125
public class CustomObjectMarshaller implements BinaryMarshaller<CustomObject> {
126
@Override
127
public byte[] marshal(CustomObject obj) {
128
// Custom serialization logic
129
ByteArrayOutputStream baos = new ByteArrayOutputStream();
130
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
131
oos.writeObject(obj);
132
return baos.toByteArray();
133
} catch (IOException e) {
134
throw new RuntimeException("Failed to marshal object", e);
135
}
136
}
137
138
@Override
139
public CustomObject unmarshal(byte[] data) {
140
// Custom deserialization logic
141
try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
142
return (CustomObject) ois.readObject();
143
} catch (Exception e) {
144
throw new RuntimeException("Failed to unmarshal object", e);
145
}
146
}
147
148
@Override
149
public int estimateSize(CustomObject object) {
150
return object.getEstimatedSize();
151
}
152
153
@Override
154
public boolean canMarshal(CustomObject object) {
155
return object.isSerializable();
156
}
157
}
158
```
159
160
### Marshaller Configuration
161
162
Configuration system for customizing marshalling behavior across different data types.
163
164
```java { .api }
165
/**
166
* Configuration for marshaller behavior and type mappings
167
*/
168
public interface MarshallerConfig {
169
/** Get marshaller for specific type */
170
<T> BinaryMarshaller<T> getMarshaller(Class<T> type);
171
172
/** Register custom marshaller for type */
173
<T> void registerMarshaller(Class<T> type, BinaryMarshaller<T> marshaller);
174
175
/** Get default marshaller for unknown types */
176
BinaryMarshaller<Object> getDefaultMarshaller();
177
178
/** Check if type has registered marshaller */
179
boolean hasMarshaller(Class<?> type);
180
181
/** Get marshalling options */
182
MarshallingOptions getOptions();
183
}
184
185
/**
186
* Default marshaller configuration with built-in type support
187
*/
188
public class DefaultMarshallerConfig implements MarshallerConfig {
189
/** Create default configuration */
190
public static DefaultMarshallerConfig create();
191
192
/** Create with custom options */
193
public static DefaultMarshallerConfig create(MarshallingOptions options);
194
}
195
196
/**
197
* Options for controlling marshalling behavior
198
*/
199
public static class MarshallingOptions {
200
/** Enable compression for large objects */
201
public final boolean compression;
202
203
/** Maximum object size for marshalling */
204
public final int maxObjectSize;
205
206
/** Charset for string encoding */
207
public final Charset defaultCharset;
208
209
/** Enable type safety checks */
210
public final boolean typeSafety;
211
212
public MarshallingOptions(boolean compression, int maxObjectSize,
213
Charset defaultCharset, boolean typeSafety);
214
}
215
```
216
217
### Isolate Management
218
219
APIs for managing native isolates and their lifecycle in bridge communications.
220
221
```java { .api }
222
/**
223
* Configuration for native isolate creation and management
224
*/
225
public static class NativeIsolateConfig {
226
/** Maximum heap size for isolate */
227
public final long maxHeapSize;
228
229
/** Initial heap size */
230
public final long initialHeapSize;
231
232
/** Stack size per thread */
233
public final int stackSize;
234
235
/** Enable debugging support */
236
public final boolean debugMode;
237
238
/** Custom isolate parameters */
239
public final Map<String, String> parameters;
240
241
public NativeIsolateConfig(long maxHeapSize, long initialHeapSize,
242
int stackSize, boolean debugMode,
243
Map<String, String> parameters);
244
245
/** Create default configuration */
246
public static NativeIsolateConfig createDefault();
247
}
248
249
/**
250
* Process-level isolate management for bridge communication
251
*/
252
public final class ProcessIsolate {
253
/** Create new process isolate with configuration */
254
public static ProcessIsolate create(NativeIsolateConfig config);
255
256
/** Get current process isolate */
257
public static ProcessIsolate getCurrent();
258
259
/** Execute operation in isolate context */
260
public <T> T execute(Callable<T> operation);
261
262
/** Execute void operation in isolate context */
263
public void execute(Runnable operation);
264
265
/** Shutdown isolate and clean up resources */
266
public void shutdown();
267
268
/** Check if isolate is active */
269
public boolean isActive();
270
271
/** Get isolate configuration */
272
public NativeIsolateConfig getConfig();
273
}
274
275
/**
276
* Exception thrown when isolate creation fails
277
*/
278
public class IsolateCreateException extends Exception {
279
public IsolateCreateException(String message);
280
public IsolateCreateException(String message, Throwable cause);
281
public IsolateCreateException(Throwable cause);
282
}
283
```
284
285
**Usage Examples:**
286
287
```java
288
public class IsolateExample {
289
public void setupIsolate() throws IsolateCreateException {
290
// Configure isolate
291
NativeIsolateConfig config = new NativeIsolateConfig(
292
1024 * 1024 * 64, // 64MB max heap
293
1024 * 1024 * 16, // 16MB initial heap
294
8192, // 8KB stack size
295
true, // Enable debugging
296
Map.of("opt.level", "3") // Custom parameters
297
);
298
299
// Create and use isolate
300
try (ProcessIsolate isolate = ProcessIsolate.create(config)) {
301
String result = isolate.execute(() -> {
302
// Execute in isolate context
303
return performComputation();
304
});
305
306
System.out.println("Result: " + result);
307
}
308
}
309
310
private String performComputation() {
311
return "Computed in isolate";
312
}
313
}
314
```
315
316
### Reference Management
317
318
Control how objects are passed between runtime environments - by value or by reference.
319
320
```java { .api }
321
/**
322
* Marker annotation for passing objects by remote reference
323
*/
324
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE})
325
@Retention(RetentionPolicy.RUNTIME)
326
public @interface ByRemoteReference {
327
/** Reference timeout in milliseconds */
328
long timeout() default 30000L;
329
330
/** Whether to cache references */
331
boolean cache() default true;
332
}
333
334
/**
335
* Force all instances of type to be passed by remote reference
336
*/
337
@Target(ElementType.TYPE)
338
@Retention(RetentionPolicy.RUNTIME)
339
public @interface AlwaysByRemoteReference {
340
/** Default timeout for all references */
341
long defaultTimeout() default 60000L;
342
}
343
344
/**
345
* Force all instances of type to be passed by local value
346
*/
347
@Target(ElementType.TYPE)
348
@Retention(RetentionPolicy.RUNTIME)
349
public @interface AlwaysByLocalReference {
350
/** Whether to validate during marshalling */
351
boolean validate() default true;
352
}
353
```
354
355
**Usage Examples:**
356
357
```java
358
// Always pass by remote reference
359
@AlwaysByRemoteReference(defaultTimeout = 120000L)
360
public class ExpensiveResource {
361
public void performOperation() {
362
// Expensive operation executed remotely
363
}
364
}
365
366
// Control reference passing per method
367
public interface ServiceBridge {
368
// Pass by local value (default)
369
String processData(String input);
370
371
// Pass by remote reference with timeout
372
void updateResource(@ByRemoteReference(timeout = 60000L) ExpensiveResource resource);
373
374
// Return by remote reference
375
@ByRemoteReference
376
ExpensiveResource createResource();
377
}
378
```
379
380
### Thread Management
381
382
Thread representation and management across different runtime environments.
383
384
```java { .api }
385
/**
386
* Represents a thread within a native isolate
387
*/
388
public interface NativeIsolateThread {
389
/** Get thread ID */
390
long getThreadId();
391
392
/** Get associated isolate */
393
Isolate getIsolate();
394
395
/** Check if thread is current thread */
396
boolean isCurrent();
397
398
/** Attach to this thread context */
399
void attach();
400
401
/** Detach from this thread context */
402
void detach();
403
404
/** Execute operation in thread context */
405
<T> T execute(Callable<T> operation);
406
}
407
408
/**
409
* Represents a thread within HotSpot isolate
410
*/
411
public interface HSIsolateThread {
412
/** Get Java thread object */
413
Thread getJavaThread();
414
415
/** Get thread name */
416
String getName();
417
418
/** Check if thread is daemon */
419
boolean isDaemon();
420
421
/** Get thread priority */
422
int getPriority();
423
424
/** Get thread state */
425
Thread.State getState();
426
427
/** Execute operation in HotSpot context */
428
<T> T execute(Callable<T> operation);
429
}
430
```
431
432
## Types
433
434
```java { .api }
435
/**
436
* Callable interface for operations that return values
437
*/
438
public interface Callable<V> {
439
V call() throws Exception;
440
}
441
442
/**
443
* Base isolate interface
444
*/
445
public interface Isolate {
446
/** Get isolate ID */
447
long getId();
448
449
/** Check if isolate is current */
450
boolean isCurrent();
451
452
/** Get isolate threads */
453
Set<IsolateThread> getThreads();
454
}
455
456
/**
457
* Base isolate thread interface
458
*/
459
public interface IsolateThread {
460
/** Get thread ID */
461
long getId();
462
463
/** Get owning isolate */
464
Isolate getIsolate();
465
}
466
467
/**
468
* Character set enumeration for string encoding
469
*/
470
public enum Charset {
471
UTF_8, UTF_16, ISO_8859_1, US_ASCII;
472
473
/** Get canonical name */
474
public String getCanonicalName();
475
476
/** Check if charset supports encoding */
477
public boolean canEncode();
478
}
479
480
/**
481
* Input/output stream interfaces for binary data
482
*/
483
public interface ByteArrayOutputStream extends AutoCloseable {
484
void write(int b);
485
void write(byte[] b);
486
byte[] toByteArray();
487
void close();
488
}
489
490
public interface ByteArrayInputStream extends AutoCloseable {
491
int read();
492
int read(byte[] b);
493
void close();
494
}
495
```