18 Create Event Stream in Process, Active
The sample StreamEventsSample.java
creates an event stream
at the same time a recording is created. An event stream is a sequence of events.
The class RecordingStream starts a recording
and creates an event stream at the same time. The sample calls
Thread.sleep(1000)
three times, which creates three
jdk.ThreadSleep
events. The Event Streaming API prints the
jdk.ThreadSleep
events when they occur:
import jdk.jfr.Configuration;
import jdk.jfr.consumer.RecordingStream;
public class StreamEventsSample {
public static void main(String... args) throws Exception {
Configuration c = Configuration.getConfiguration("profile");
try (RecordingStream rs = new RecordingStream(c)) {
rs.onEvent("jdk.ThreadSleep", System.out::println);
System.out.println("Starting recording stream ...");
rs.startAsync();
for (int i = 0; i < 3; i++) {
System.out.println("Sleeping for 1s...");
Thread.sleep(1000);
}
}
}
}
Run StreamEventsSample
with the following command:
java -XX:StartFlightRecording StreamEventsSample.java
It prints output similar to the following:
Started recording 1. No limit specified, using maxsize=250MB as default.
Use jcmd 7400 JFR.dump name=1 filename=FILEPATH to copy recording data to file.
Starting recording stream ...
Sleeping for 1s...
Sleeping for 1s...
jdk.ThreadSleep {
startTime = 00:26:42.463
duration = 2.14 s
time = 1.00 s
...
}
Sleeping for 1s...
jdk.ThreadSleep {
startTime = 00:26:44.602
duration = 1.04 s
time = 1.00 s
...
}
Follow these steps to create an event stream from a recording with the RecordingStream class:
- Optionally specify a predefined configuration ("default" or "profile") with the Configuration class.
- Create a RecordingStream instance with either the Configuration.getConfiguration() or Configuration.getConfiguration(Configuration) method.
- Optionally enable events that you want to include in the event stream
with the
RecordingStream::enable(String)
method. -
Specify actions to perform on events in the stream. To specify an action to perform on all events, use the onEvent(Consumer<RecordedEvent>) method. For example, the following statement prints the name of all events in the stream to standard output:
rs.onEvent(e -> { System.out.println(e.getEventType().getName()); });
Use the onEvent(String, Consumer<RecordedEvent>) to specify an action to perform on a specific event. For example, the following statement prints events whose name matches jdk.ThreadSleep:rs.onEvent("jdk.ThreadSleep", System.out::println);
- Start the event stream with either the start() or startAsync() method. This sample calls startAsync(), which runs the stream in a background thread. If you call the start() method, then the application will not proceed pass this method call until the stream is closed.