- GraalVM for JDK 23 (Latest)
- GraalVM for JDK 24 (Early Access)
- GraalVM for JDK 21
- GraalVM for JDK 17
- Archives
- Dev Build
Embedding Insight into Applications
Embedding Insight into Java #
Graal languages (languages implemented with the Truffle framework, such as JavaScript, Python, Ruby, and R) can be embedded into custom Java applications via Polyglot Context API. GraalVM Insight can also be controlled via the same API. Like:
final Engine engine = context.getEngine();
Instrument instrument = engine.getInstruments().get("insight");
Function<Source, AutoCloseable> access = instrument.lookup(Function.class);
AutoCloseable handle = access.apply(agentSrc);
Obtain Engine
for Context
and ask for the insight
instrument.
Then create `Source` with the GraalVM Insight script and apply it while obtaining its instrumentation handle.
Use `handle.close()` to disable all the script's instrumentation when no longer needed.
For Example:
```java
Source instrument = Source.create("js", """
insight.on('return', function(ctx, frame) {
console.log(`Instrumented where = ${frame.where}`);
}, {
roots: true,
rootNameFilter: 'end',
});
""");
Source script = Source.create("js", """
function end() {
var where = 'end';
console.log(where + ' invoked')
}
end();
""");
try (Context context = Context.newBuilder().build()) {
@SuppressWarnings("unchecked")
Function<Source, AutoCloseable> insight = context.getEngine().getInstruments().get("insight").lookup(Function.class);
// run without instrumentation
context.eval(script);
// run with instrumentation
try (AutoCloseable handle = insight.apply(instrument)) {
context.eval(script);
}
// run without instrumentation
context.eval(script);
}
```
See [Embedding Dependency Setup](/latest/reference-manual/embed-languages/#dependency-setup). Add a dependency on `insight`:
```