or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

c-interop.mdcollections.mdconfig.mdindex.mdjni-utils.mdnative-bridge.mdnative-image.mdpolyglot.mdsubstitutions.mdword.md

native-image.mddocs/

0

# Native Image Compilation

1

2

APIs for ahead-of-time (AOT) compilation of Java applications to native executables, with runtime customization, build-time optimization, and system integration capabilities.

3

4

## Capabilities

5

6

### Runtime Information

7

8

Core APIs for detecting execution context and native image properties at runtime.

9

10

```java { .api }

11

/**

12

* Provides information about the current execution environment

13

*/

14

public final class ImageInfo {

15

/** Check if code is running in any image context (build-time or runtime) */

16

public static boolean inImageCode();

17

18

/** Check if code is running during image build process */

19

public static boolean inImageBuildtimeCode();

20

21

/** Check if code is running in compiled native image */

22

public static boolean inImageRuntimeCode();

23

24

/** Check if image is an executable (vs shared library) */

25

public static boolean isExecutable();

26

27

/** Check if image is a shared library */

28

public static boolean isSharedLibrary();

29

30

/** Property key for detecting image code context */

31

public static final String PROPERTY_IMAGE_CODE_KEY = "org.graalvm.nativeimage.imagecode";

32

33

/** Property values for image code detection */

34

public static final String PROPERTY_IMAGE_CODE_VALUE_BUILDTIME = "buildtime";

35

public static final String PROPERTY_IMAGE_CODE_VALUE_RUNTIME = "runtime";

36

}

37

```

38

39

**Usage Examples:**

40

41

```java

42

public class RuntimeDetection {

43

public static void configureBasedOnContext() {

44

if (ImageInfo.inImageBuildtimeCode()) {

45

// Configuration during native image build

46

System.out.println("Configuring for native image build");

47

48

} else if (ImageInfo.inImageRuntimeCode()) {

49

// Runtime behavior in native image

50

System.out.println("Running in native image");

51

52

} else {

53

// Regular JVM execution

54

System.out.println("Running on JVM");

55

}

56

57

if (ImageInfo.isExecutable()) {

58

System.out.println("This is a native executable");

59

}

60

}

61

}

62

```

63

64

### Singleton Registry

65

66

Centralized registry for sharing singleton objects across the native image, replacing traditional static fields.

67

68

```java { .api }

69

/**

70

* Registry for singleton objects available throughout native image execution

71

*/

72

public final class ImageSingletons {

73

/** Register singleton instance for given key type */

74

public static <T> void add(Class<T> key, T value);

75

76

/** Lookup singleton instance by key type */

77

public static <T> T lookup(Class<T> key);

78

79

/** Check if singleton is registered for key type */

80

public static boolean contains(Class<?> key);

81

}

82

```

83

84

**Usage Examples:**

85

86

```java

87

// Define service interface

88

interface DatabaseConfig {

89

String getConnectionUrl();

90

}

91

92

// Register during image build

93

public class DatabaseConfigFeature implements Feature {

94

@Override

95

public void afterRegistration(AfterRegistrationAccess access) {

96

DatabaseConfig config = new ProductionDatabaseConfig();

97

ImageSingletons.add(DatabaseConfig.class, config);

98

}

99

}

100

101

// Use at runtime

102

public class DatabaseService {

103

private final DatabaseConfig config;

104

105

public DatabaseService() {

106

this.config = ImageSingletons.lookup(DatabaseConfig.class);

107

}

108

109

public void connect() {

110

String url = config.getConnectionUrl();

111

// Connect to database...

112

}

113

}

114

```

115

116

### Isolate Management

117

118

APIs for managing isolated heaps and threads in native images, enabling memory isolation and multi-tenancy.

119

120

```java { .api }

121

/**

122

* Represents an isolated heap in native image

123

*/

124

public interface Isolate extends PointerBase {

125

/** Check if isolate pointer is null */

126

boolean isNull();

127

}

128

129

/**

130

* Represents a thread within an isolate

131

*/

132

public interface IsolateThread extends PointerBase {

133

/** Check if isolate thread pointer is null */

134

boolean isNull();

135

}

136

137

/**

138

* Access to current isolate and thread

139

*/

140

public final class CurrentIsolate {

141

/** Get current isolate thread */

142

public static IsolateThread getCurrentThread();

143

144

/** Get current isolate */

145

public static Isolate getIsolate();

146

}

147

148

/**

149

* Thread management utilities for native images

150

*/

151

public final class Threading {

152

/** Check if current thread is main thread */

153

public static boolean isMainThread();

154

155

/** Get thread-local storage */

156

public static ThreadLocal<Object> getThreadLocalStorage();

157

158

/** Create new thread in current isolate */

159

public static Thread createThread(Runnable task);

160

161

/** Join thread execution */

162

public static void joinThread(Thread thread);

163

}

164

165

/**

166

* VM runtime operations and lifecycle management

167

*/

168

public final class VMRuntime {

169

/** Initialize VM runtime */

170

public static void initialize();

171

172

/** Shutdown VM runtime */

173

public static void shutdown();

174

175

/** Register shutdown hook */

176

public static void addShutdownHook(Runnable hook);

177

178

/** Get VM version information */

179

public static String getVersion();

180

181

/** Check if VM is running */

182

public static boolean isRunning();

183

}

184

```

185

186

### Object Handle Management

187

188

Safe references to managed objects that survive garbage collection, essential for JNI and native code interaction.

189

190

```java { .api }

191

/**

192

* Handle to a managed object that prevents garbage collection

193

*/

194

public interface ObjectHandle extends ComparableWord {

195

/** Check if handle is null */

196

boolean isNull();

197

198

/** Get underlying object from handle */

199

Object getObject();

200

}

201

202

/**

203

* Factory for creating and managing object handles

204

*/

205

public final class ObjectHandles {

206

/** Create handle for object */

207

public ObjectHandle create(Object object);

208

209

/** Get global object handles instance */

210

public static ObjectHandles getGlobal();

211

212

/** Get null handle constant */

213

public static ObjectHandle nullHandle();

214

215

/** Destroy handle and allow object to be collected */

216

public void destroy(ObjectHandle handle);

217

}

218

```

219

220

### Memory Pinning

221

222

Prevent garbage collector from moving objects, enabling safe access from native code.

223

224

```java { .api }

225

/**

226

* Prevents GC from moving an object, allowing safe native access

227

*/

228

public interface PinnedObject extends AutoCloseable {

229

/** Get address of array element at given index */

230

<T> Pointer addressOfArrayElement(int index);

231

232

/** Release pin and allow object to be moved */

233

void close();

234

}

235

```

236

237

**Usage Examples:**

238

239

```java

240

public class NativeMemoryAccess {

241

public void processArray(byte[] data) {

242

// Pin array for native access

243

try (PinnedObject pinned = PinnedObject.create(data)) {

244

Pointer address = pinned.addressOfArrayElement(0);

245

246

// Pass address to native function

247

processNativeData(address, data.length);

248

} // Automatically unpinned

249

}

250

251

// Native method declaration

252

private native void processNativeData(Pointer data, int length);

253

}

254

```

255

256

### Platform Detection

257

258

APIs for detecting target platform characteristics and making platform-specific decisions.

259

260

```java { .api }

261

/**

262

* Platform detection with nested marker interfaces for specific platforms

263

*/

264

public interface Platform {

265

// Nested platform marker interfaces

266

interface HOSTED_ONLY extends Platform {}

267

interface LINUX extends Platform {}

268

interface DARWIN extends Platform {}

269

interface WINDOWS extends Platform {}

270

interface AMD64 extends Platform {}

271

interface AARCH64 extends Platform {}

272

273

// Combined platform markers

274

interface LINUX_AMD64 extends LINUX, AMD64 {}

275

interface DARWIN_AMD64 extends DARWIN, AMD64 {}

276

interface WINDOWS_AMD64 extends WINDOWS, AMD64 {}

277

}

278

```

279

280

### Build-Time Customization

281

282

Feature interface for customizing native image generation process with hooks for different build phases.

283

284

```java { .api }

285

/**

286

* Interface for customizing native image generation process

287

*/

288

public interface Feature {

289

/** Called after all features are registered */

290

default void afterRegistration(AfterRegistrationAccess access) {}

291

292

/** Called before static analysis begins */

293

default void beforeAnalysis(BeforeAnalysisAccess access) {}

294

295

/** Called during iterative analysis phase */

296

default void duringAnalysis(DuringAnalysisAccess access) {}

297

298

/** Called after analysis is complete */

299

default void afterAnalysis(AfterAnalysisAccess access) {}

300

301

/** Called before heap creation */

302

default void beforeCompilation(BeforeCompilationAccess access) {}

303

304

/** Called after image heap is created */

305

default void afterImageWrite(AfterImageWriteAccess access) {}

306

307

/** Get feature description */

308

default String getDescription() {

309

return getClass().getName();

310

}

311

312

// Nested access interfaces for different build phases

313

interface AfterRegistrationAccess {

314

<T> void registerClassForReflection(Class<T> clazz);

315

void registerMethodForReflection(Method method);

316

void registerFieldForReflection(Field field);

317

}

318

319

interface BeforeAnalysisAccess extends FeatureAccess {

320

void registerAsUsed(Class<?> clazz);

321

void registerAsInstantiated(Class<?> clazz);

322

void registerAsReachable(Executable executable);

323

}

324

325

interface DuringAnalysisAccess extends FeatureAccess {

326

void requireAnalysisIteration();

327

}

328

329

interface FeatureAccess {

330

Class<?> findClassByName(String className);

331

List<Class<?>> findSubclasses(Class<?> baseClass);

332

ApplicationClassLoader getApplicationClassLoader();

333

}

334

}

335

```

336

337

**Usage Examples:**

338

339

```java

340

@AutomaticFeature

341

public class CustomSerializationFeature implements Feature {

342

@Override

343

public void beforeAnalysis(BeforeAnalysisAccess access) {

344

// Register classes for reflection

345

access.registerClassForReflection(MySerializableClass.class);

346

347

// Find and register all serializable classes

348

for (Class<?> clazz : access.findSubclasses(Serializable.class)) {

349

access.registerAsInstantiated(clazz);

350

}

351

}

352

353

@Override

354

public void afterRegistration(AfterRegistrationAccess access) {

355

// Register singleton services

356

MyService service = new MyService();

357

ImageSingletons.add(MyService.class, service);

358

}

359

}

360

```

361

362

### Field Value Transformation

363

364

Transform static field values during image build time for optimization and configuration.

365

366

```java { .api }

367

/**

368

* Interface for transforming field values during image generation

369

*/

370

public interface FieldValueTransformer {

371

/** Transform field value during image build */

372

Object transform(Object receiver, Object originalValue);

373

}

374

```

375

376

### Logging Support

377

378

Custom logging integration for native images with efficient log handling.

379

380

```java { .api }

381

/**

382

* Custom log handler for native image logging

383

*/

384

public interface LogHandler {

385

/** Log message with specified log level */

386

void log(LogLevel level, String message);

387

388

/** Flush any buffered log output */

389

void flush();

390

}

391

392

/**

393

* Log levels for native image logging

394

*/

395

public enum LogLevel {

396

ERROR(1),

397

WARNING(2),

398

INFO(3),

399

DEBUG(4);

400

401

private final int level;

402

403

LogLevel(int level) {

404

this.level = level;

405

}

406

407

public int getLevel() {

408

return level;

409

}

410

}

411

```

412

413

## Types

414

415

```java { .api }

416

// Automatic feature registration annotation

417

@Target(ElementType.TYPE)

418

@Retention(RetentionPolicy.RUNTIME)

419

public @interface AutomaticFeature {

420

}

421

422

// Base word types for low-level operations

423

public interface WordBase {

424

}

425

426

public interface ComparableWord extends WordBase {

427

boolean equal(ComparableWord val);

428

boolean notEqual(ComparableWord val);

429

}

430

431

// Pointer base interface

432

public interface PointerBase extends ComparableWord {

433

boolean isNull();

434

boolean isNonNull();

435

}

436

```