19 Create Event Stream in Process, Passive
The sample PassiveEventStreamSample.java
starts a passive
event stream with the method EventStream.openRepository().
As with any event stream, a passive event stream listens for events; in this example, it
listens for jdk.CPULoad
events. However, what gets recorded is controlled
by external means, for example, by the command-line option
-XX:StartFlightRecording
, the jcmd
command JFR.start, or an API (for example, Recording::start()).
The sample PassiveEventStreamSample.java
creates an event
stream not with RecordingStream but with EventStream.openRepository(). An event stream requires a
recording; this sample obtains it from the command-line option
-XX:StartFlightRecording
.
import java.util.concurrent.atomic.AtomicInteger;
import jdk.jfr.consumer.EventStream;
public class PassiveEventStreamSample {
static int NUMBER_CPULOAD_EVENTS = 3;
public static void main(String... args) throws Exception {
AtomicInteger timer = new AtomicInteger();
try (EventStream es = EventStream.openRepository()) {
es.onEvent("jdk.CPULoad", event -> {
System.out.println("CPU Load " + event.getEndTime());
System.out.println(" Machine total: "
+ 100 * event.getFloat("machineTotal") + "%");
System.out.println(
" JVM User: " + 100 * event.getFloat("jvmUser") +
"%");
System.out.println(
" JVM System: " + 100 * event.getFloat("jvmSystem") +
"%");
System.out.println();
if (timer.incrementAndGet() == NUMBER_CPULOAD_EVENTS) {
System.exit(0);
}
});
es.start();
}
}
}
Run PassiveEventStreamSample
with the following command:
java -XX:StartFlightRecording PassiveEventStreamSample.java
It prints output similar to the following:
Started recording 1. No limit specified, using maxsize=250MB as default.
Use jcmd 12352 JFR.dump name=1 filename=FILEPATH to copy recording data to file.
CPU Load 2020-01-24T05:34:36.265584686Z
Machine total: 19.3799%
JVM User: 5.2175264%
JVM System: 1.8634024%
CPU Load 2020-01-24T05:34:37.310049859Z
Machine total: 5.2533073%
JVM User: 0.0%
JVM System: 0.3899041%
CPU Load 2020-01-24T05:34:38.373796070Z
Machine total: 7.242967%
JVM User: 0.0%
JVM System: 1.1451485%