AutoCloseable
RecordingStream
, RemoteRecordingStream
public interface EventStream extends AutoCloseable
A stream is a sequence of events and the way to interact with a stream is to register actions. The EventStream
interface is not to be implemented and future versions of the JDK may prevent this completely.
To receive a notification when an event arrives, register an action using the onEvent(Consumer)
method. To filter the stream for an event with a specific name, use onEvent(String, Consumer)
method.
By default, the same RecordedEvent
object can be used to represent two or more distinct events. That object can be delivered multiple times to the same action as well as to other actions. To use an event object after the action is completed, the setReuse(boolean)
method should be set to false
so a new object is allocated for each event.
Events are delivered in batches. To receive a notification when a batch is complete, register an action using the onFlush(Runnable)
method. This is an opportunity to aggregate or push data to external systems while the Java Virtual Machine (JVM) is preparing the next batch.
Events within a batch are sorted chronologically by their end time. Well-ordering of events is only maintained for events available to the JVM at the point of flush, i.e. for the set of events delivered as a unit in a single batch. Events delivered in a batch could therefore be out-of-order compared to events delivered in a previous batch, but never out-of-order with events within the same batch. If ordering is not a concern, sorting can be disabled using the setOrdered(boolean)
method.
To dispatch events to registered actions, the stream must be started. To start processing in the current thread, invoke the start()
method. To process actions asynchronously in a separate thread, invoke the startAsync()
method. To await completion of the stream, use the awaitTermination awaitTermination()
or the awaitTermination(Duration)
method.
When a stream ends it is automatically closed. To manually stop processing of events, close the stream by invoking the close()
method. A stream can also be automatically closed in exceptional circumstances, for example if the JVM that is being monitored exits. To receive a notification in any of these occasions, use the onClose(Runnable)
method to register an action.
If an unexpected exception occurs in an action, it is possible to catch the exception in an error handler. An error handler can be registered using the onError(Consumer)
method. If no error handler is registered, the default behavior is to print the exception and its backtrace to the standard error stream.
The following example shows how an EventStream
can be used to listen to events on a JVM running Flight Recorder
try (var 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();
});
es.onEvent("jdk.GarbageCollection", event -> {
System.out.println("Garbage collection: " + event.getLong("gcId"));
System.out.println(" Cause: " + event.getString("cause"));
System.out.println(" Total pause: " + event.getDuration("sumOfPauses"));
System.out.println(" Longest pause: " + event.getDuration("longestPause"));
System.out.println();
});
es.start();
}
To start recording together with the stream, see RecordingStream
.
Modifier and Type | Method | Description |
---|---|---|
void |
awaitTermination() |
Blocks until all actions are completed, or the stream is closed, or the current thread is interrupted, whichever happens first. |
void |
awaitTermination |
Blocks until all actions are completed, or the stream is closed, or the timeout occurs, or the current thread is interrupted, whichever happens first. |
void |
close() |
Releases all resources associated with this stream. |
void |
onClose |
Registers an action to perform when the stream is closed. |
void |
onError |
Registers an action to perform if an exception occurs. |
void |
onEvent |
Registers an action to perform on all events matching a name. |
void |
onEvent |
Registers an action to perform on all events in the stream. |
void |
onFlush |
Registers an action to perform after the stream has been flushed. |
default void |
onMetadata |
Registers an action to perform when new metadata arrives in the stream. |
static EventStream |
openFile |
Creates an event stream from a file. |
static EventStream |
openRepository() |
Creates a stream from the repository of the current Java Virtual Machine (JVM). |
static EventStream |
openRepository |
Creates an event stream from a disk repository. |
boolean |
remove |
Unregisters an action. |
void |
setEndTime |
Specifies the end time of the stream. |
void |
setOrdered |
Specifies that events arrives in chronological order, sorted by the time they were committed to the stream. |
void |
setReuse |
Specifies that the event object in an onEvent(Consumer) action can be reused. |
void |
setStartTime |
Specifies the start time of the stream. |
void |
start() |
Starts processing of actions. |
void |
startAsync() |
Starts asynchronous processing of actions. |
static EventStream openRepository() throws IOException
By default, the stream starts with the next event flushed by Flight Recorder.
null
IOException
- if a stream can't be opened, or an I/O error occurs when trying to access the repositorySecurityException
- if a security manager exists and the caller does not have FlightRecorderPermission("accessFlightRecorder")
static EventStream openRepository(Path directory) throws IOException
By default, the stream starts with the next event flushed by Flight Recorder.
Only trusted disk repositories should be opened.
directory
- location of the disk repository, not null
null
IOException
- if a stream can't be opened, or an I/O error occurs when trying to access the repositorySecurityException
- if a security manager exists and its checkRead
method denies read access to the directory, or files in the directory.static EventStream openFile(Path file) throws IOException
By default, the stream starts with the first event in the file.
Only recording files from trusted sources should be opened.
file
- location of the file, not null
null
IOException
- if the file can't be opened, or an I/O error occurs during readingSecurityException
- if a security manager exists and its checkRead
method denies read access to the filedefault void onMetadata(Consumer<MetadataEvent> action)
The following example shows how to listen to new event types, register an action if the event type name matches a regular expression and increase a counter if a matching event is found. A benefit of using an action per event type, instead of the generic onEvent(Consumer)
method, is that a stream implementation can avoid reading events that are of no interest.
static long count = 0;
public static void main(String... args) throws IOException {
Path file = Path.of(args[0]);
String regExp = args[1];
var pr = Pattern.compile(regExp).asMatchPredicate();
try (var s = EventStream.openFile(file)) {
s.setOrdered(false);
s.onMetadata(metadata -> metadata.getAddedEventTypes()
.stream().map(EventType::getName).filter(pr)
.forEach(eventName -> s.onEvent(eventName, event -> count++)));
s.start();
System.out.println(count + " events matches " + regExp);
}
}
action
- to perform, not null
IllegalStateException
- if an action is added after the stream has startedvoid onEvent(Consumer<RecordedEvent> action)
To perform an action on a subset of event types, consider using onEvent(String, Consumer)
and onMetadata(Consumer)
as it is likely more performant than any selection or filtering mechanism implemented in a generic action.
action
- an action to perform on each RecordedEvent
, not null
void onEvent(String eventName, Consumer<RecordedEvent> action)
eventName
- the name of the event, not null
action
- an action to perform on each RecordedEvent
matching the event name, not null
void onFlush(Runnable action)
action
- an action to perform after the stream has been flushed, not null
void onError(Consumer<Throwable> action)
If an action is not registered, an exception stack trace is printed to standard error.
Registering an action overrides the default behavior. If multiple actions have been registered, they are performed in the order of registration.
If this method itself throws an exception, resulting behavior is undefined.
action
- an action to perform if an exception occurs, not null
void onClose(Runnable action)
If the stream is already closed, the action will be performed immediately in the current thread.
action
- an action to perform after the stream is closed, not null
void close()
If a stream is started, asynchronously or synchronously, it is stopped immediately or after the next flush. This method does NOT guarantee that all registered actions are completed before return.
Closing a previously closed stream has no effect.
close
in interface AutoCloseable
boolean remove(Object action)
If the action has been registered multiple times, all instances are unregistered.
action
- the action to unregister, not null
true
if the action was unregistered, false
otherwisevoid setReuse(boolean reuse)
onEvent(Consumer)
action can be reused. If reuse is set to true
, an action should not keep a reference to the event object after the action has completed.
reuse
- true
if an event object can be reused, false
otherwisevoid setOrdered(boolean ordered)
ordered
- if event objects arrive in chronological order to onEvent(Consumer)
void setStartTime(Instant startTime)
The start time must be set before starting the stream
startTime
- the start time, not null
IllegalStateException
- if the stream is already startedvoid setEndTime(Instant endTime)
The end time must be set before starting the stream.
At end time, the stream is closed.
endTime
- the end time, not null
IllegalStateException
- if the stream is already startedvoid start()
Actions are performed in the current thread.
To stop the stream, use the close()
method.
IllegalStateException
- if the stream is already started or closedvoid startAsync()
Actions are performed in a single separate thread.
To stop the stream, use the close()
method.
IllegalStateException
- if the stream is already started or closedvoid awaitTermination(Duration timeout) throws InterruptedException
timeout
- the maximum time to wait, not null
IllegalArgumentException
- if timeout is negativeInterruptedException
- if interrupted while waitingvoid awaitTermination() throws InterruptedException
InterruptedException
- if interrupted while waiting
© 1993, 2023, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/21/docs/api/jdk.jfr/jdk/jfr/consumer/EventStream.html