7 Dynamic Events
Dynamic events enable you to define events at run time, including their annotations and fields.
Note:
Only use dynamic events if you won't know the layout of an event until you run your application.The example DynamicSample.java
creates a dynamic
event named com.oracle.RandomString
, which includes a field
whose name is a random string:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jdk.jfr.AnnotationElement;
import jdk.jfr.Category;
import jdk.jfr.Description;
import jdk.jfr.Event;
import jdk.jfr.EventFactory;
import jdk.jfr.Label;
import jdk.jfr.Name;
import jdk.jfr.ValueDescriptor;
public class DynamicSample {
private static String randomString(int n) {
var ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var builder = new StringBuilder();
while (n-- != 0) {
int character = (int) (Math.random()
* ALPHA_NUMERIC_STRING.length());
builder.append(ALPHA_NUMERIC_STRING.charAt(character));
}
return builder.toString();
}
public static void main(String[] args) {
String[] category = { "Demonstration", "Tutorial" };
var eventAnnotations = new ArrayList<AnnotationElement>();
eventAnnotations
.add(new AnnotationElement(
Name.class, "com.oracle.RandomString"));
eventAnnotations.add(new AnnotationElement(Label.class,
"Field Named with Random String"));
eventAnnotations.add(new AnnotationElement(Description.class,
"Demonstrates how to create a dynamic event"));
eventAnnotations.add(new AnnotationElement(
Category.class, category));
var fields = new ArrayList<ValueDescriptor>();
var messageAnnotations = Collections
.singletonList(new AnnotationElement(Label.class, "Message"));
var randomFieldName = DynamicSample.randomString(8);
fields.add(new ValueDescriptor(String.class, randomFieldName,
messageAnnotations));
var numberAnnotations = Collections
.singletonList(new AnnotationElement(Label.class, "Number"));
fields.add(new ValueDescriptor(
int.class, "number", numberAnnotations));
var f = EventFactory.create(eventAnnotations, fields);
Event event = f.newEvent();
event.set(0, "hello, world!");
event.set(1, 100);
event.commit();
}
}
Run DynamicSample
with the following commands:
java -XX:StartFlightRecording:filename=d.jfr DynamicSample.java
jfr print --events RandomString d.jfr
The last command prints output similar to the following:
com.oracle.RandomString {
startTime = 12:56:32.782
ZZEIUMTG = "hello, world!"
number = 100
...
}
To create a dynamic event, call the static method EventFactory.create<List<AnnotationElement>, List<ValueDescriptor>):
var f = EventFactory.create(eventAnnotations, fields);
The first argument is a list of your event's annotations, which may include built-in annotations such as @Name and @Description.
The second argument is a list of your event's fields. Define them with the ValueDescriptor class.