APIdia Launch Partner
Top Description Inners Fields Constructors Methods
jdk.management.jfr

public final Class RemoteRecordingStream

extends Object
implements EventStream
Class Inheritance
All Implemented Interfaces
jdk.jfr.consumer.EventStream, java.lang.AutoCloseable
Imports
java.io.IOException, .RandomAccessFile, java.nio.channels.FileChannel, java.nio.file.Files, .Path, .Paths, .StandardOpenOption, java.time.Duration, .Instant, java.util.ArrayList, .Collections, .HashMap, .List, .Map, .Objects, java.util.concurrent.Future, java.util.function.Consumer, javax.management.JMX, .MBeanServerConnection, .ObjectName, jdk.jfr.Configuration, .EventSettings, .EventType, .Recording, .RecordingState, jdk.jfr.consumer.EventStream, .MetadataEvent, .RecordedEvent, .RecordingStream, jdk.jfr.internal.management.EventSettingsModifier, .ManagementSupport, .StreamBarrier, .EventByteStream, jdk.management.jfr.DiskRepository.DiskChunk

An implementation of an EventStream that can serialize events over the network using an MBeanServerConnection.

The following example shows how to record garbage collection pauses and CPU usage on a remote host and print the events to standard out.

    String host = "com.example";
    int port = 4711;

    String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";

    JMXServiceURL u = new JMXServiceURL(url);
    JMXConnector c = JMXConnectorFactory.connect(u);
    MBeanServerConnection conn = c.getMBeanServerConnection();

    try (var rs = new RemoteRecordingStream(conn)) {
        rs.enable("jdk.GCPhasePause").withoutThreshold();
        rs.enable("jdk.CPULoad").withPeriod(Duration.ofSeconds(1));
        rs.onEvent("jdk.CPULoad", System.out::println);
        rs.onEvent("jdk.GCPhasePause", System.out::println);
        rs.start();
    }
    
Since
16

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
pack-priv static class

Field Summary

Modifier and TypeField and Description
pack-priv volatile boolean
pack-priv final Instant
private static final String
pack-priv volatile Instant
pack-priv final Object
private Duration
private long
pack-priv final FlightRecorderMXBean
private static final ObjectName
pack-priv final Path
pack-priv final long
pack-priv final DiskRepository
private boolean
pack-priv volatile Instant
pack-priv final EventStream

Constructor Summary

AccessConstructor and Description
public
RemoteRecordingStream(MBeanServerConnection
the MBeanServerConnection where the FlightRecorderMXBean is registered, not null
connection
)

Creates an event stream that operates against a MBeanServerConnection that has a registered FlightRecorderMXBean.

public
RemoteRecordingStream(MBeanServerConnection
the MBeanServerConnection where the FlightRecorderMXBean is registered, not null
connection
,
Path
the directory to store event data that is downloaded, not null
directory
)

Creates an event stream that operates against a MBeanServerConnection that has a registered FlightRecorderMXBean.

private
RemoteRecordingStream(MBeanServerConnection connection, Path directory, boolean delete)

Method Summary

Modifier and TypeMethod and Description
public void
awaitTermination(Duration timeout)

Implements jdk.jfr.consumer.EventStream.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.

public void
awaitTermination()

Implements jdk.jfr.consumer.EventStream.awaitTermination.

Blocks until all actions are completed, or the stream is closed, or the current thread is interrupted, whichever happens first.

private static void
checkFileAccess(Path directory)

public void
close()

Implements jdk.jfr.consumer.EventStream.close.

Releases all resources associated with this stream.

private static void
private List<Configuration>
private static FlightRecorderMXBean
private long
public EventSettings

Returns:

an event setting for further configuration, not null
disable
(String
the settings for the event, not null
name
)

Disables event with the specified name.

public void
dump(Path
the location where recording data is written, not null
destination
)

Writes recording data to a file.

public EventSettings

Returns:

an event setting for further configuration, not null
enable
(String
the settings for the event, not null
name
)

Enables the event with the specified name.

private void
private RecordingInfo
pack-priv boolean
private static Path
public void
onClose(Runnable action)

Implements jdk.jfr.consumer.EventStream.onClose.

Registers an action to perform when the stream is closed.

public void
onError(Consumer<Throwable> action)

Implements jdk.jfr.consumer.EventStream.onError.

Registers an action to perform if an exception occurs.

public void
onEvent(Consumer<RecordedEvent> action)

Implements jdk.jfr.consumer.EventStream.onEvent.

Registers an action to perform on all events in the stream.

public void
onEvent(String eventName, Consumer<RecordedEvent> action)

Implements jdk.jfr.consumer.EventStream.onEvent.

Registers an action to perform on all events matching a name.

public void
onFlush(Runnable action)

Implements jdk.jfr.consumer.EventStream.onFlush.

Registers an action to perform after the stream has been flushed.

public void
onMetadata(Consumer<MetadataEvent> action)

Overrides default jdk.jfr.consumer.EventStream.onMetadata.

Registers an action to perform when new metadata arrives in the stream.

public boolean
remove(Object action)

Implements jdk.jfr.consumer.EventStream.remove.

Unregisters an action.

public void
setEndTime(Instant endTime)

Implements jdk.jfr.consumer.EventStream.setEndTime.

Specifies the end time of the stream.

public void
setMaxAge(Duration
the length of time that data is kept, or null if infinite
maxAge
)

Determines how far back data is kept for the stream.

public void
setMaxSize(long
the amount of data to retain, 0 if infinite
maxSize
)

Determines how much data is kept for the stream.

public void
setOrdered(boolean ordered)

Implements jdk.jfr.consumer.EventStream.setOrdered.

Specifies that events arrive in chronological order, sorted by the time they were committed to the stream.

public void
setReuse(boolean reuse)

Implements jdk.jfr.consumer.EventStream.setReuse.

Specifies that the event object in an onEvent(Consumer) action can be reused.

public void
setSettings(Map<String, String>
the settings to set, not null
settings
)

Replaces all settings for this recording stream.

public void
setStartTime(Instant startTime)

Implements jdk.jfr.consumer.EventStream.setStartTime.

Specifies the start time of the stream.

public void
start()

Implements jdk.jfr.consumer.EventStream.start.

Starts processing of actions.

public void
startAsync()

Implements jdk.jfr.consumer.EventStream.startAsync.

Starts asynchronous processing of actions.

private void
public boolean

Returns:

true if recording is stopped, false otherwise
stop
()

Stops the recording stream.

private void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

closedback to summary
pack-priv volatile boolean closed
creationTimeback to summary
pack-priv final Instant creationTime
ENABLEDback to summary
private static final String ENABLED
endTimeback to summary
pack-priv volatile Instant endTime
lockback to summary
pack-priv final Object lock
maxAgeback to summary
private Duration maxAge
maxSizeback to summary
private long maxSize
mbeanback to summary
pack-priv final FlightRecorderMXBean mbean
OBJECT_NAMEback to summary
private static final ObjectName OBJECT_NAME
pathback to summary
pack-priv final Path path
recordingIdback to summary
pack-priv final long recordingId
repositoryback to summary
pack-priv final DiskRepository repository
startedback to summary
private boolean started
startTimeback to summary
pack-priv volatile Instant startTime
streamback to summary
pack-priv final EventStream stream

Constructor Detail

RemoteRecordingStreamback to summary
public RemoteRecordingStream(MBeanServerConnection connection) throws IOException

Creates an event stream that operates against a MBeanServerConnection that has a registered FlightRecorderMXBean.

To configure event settings, use setSettings(Map).

Parameters
connection:MBeanServerConnection

the MBeanServerConnection where the FlightRecorderMXBean is registered, not null

Exceptions
IOException:
if a stream can't be opened, an I/O error occurs when trying to access the repository or the FlightRecorderMXBean
RemoteRecordingStreamback to summary
public RemoteRecordingStream(MBeanServerConnection connection, Path directory) throws IOException

Creates an event stream that operates against a MBeanServerConnection that has a registered FlightRecorderMXBean.

To configure event settings, use setSettings(Map).

Parameters
connection:MBeanServerConnection

the MBeanServerConnection where the FlightRecorderMXBean is registered, not null

directory:Path

the directory to store event data that is downloaded, not null

Exceptions
IOException:
if a stream can't be opened, an I/O error occurs when trying to access the repository or the FlightRecorderMXBean
RemoteRecordingStreamback to summary
private RemoteRecordingStream(MBeanServerConnection connection, Path directory, boolean delete) throws IOException

Method Detail

awaitTerminationback to summary
public void awaitTermination(Duration timeout) throws InterruptedException

Implements jdk.jfr.consumer.EventStream.awaitTermination.

Doc from jdk.jfr.consumer.EventStream.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.

Annotations
@Override
Exceptions
InterruptedException:
if interrupted while waiting
awaitTerminationback to summary
public void awaitTermination() throws InterruptedException

Implements jdk.jfr.consumer.EventStream.awaitTermination.

Doc from jdk.jfr.consumer.EventStream.awaitTermination.

Blocks until all actions are completed, or the stream is closed, or the current thread is interrupted, whichever happens first.

Annotations
@Override
Exceptions
InterruptedException:
if interrupted while waiting
checkFileAccessback to summary
private static void checkFileAccess(Path directory) throws IOException
closeback to summary
public void close()

Implements jdk.jfr.consumer.EventStream.close.

Doc from jdk.jfr.consumer.EventStream.close.

Releases all resources associated with this stream.

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.

Annotations
@Override
closeSilentlyback to summary
private static void closeSilently(RandomAccessFile f)
configurationsback to summary
private List<Configuration> configurations(FlightRecorderMXBean mbean)
createProxyback to summary
private static FlightRecorderMXBean createProxy(MBeanServerConnection connection) throws IOException
createRecordingback to summary
private long createRecording() throws IOException
disableback to summary
public EventSettings disable(String name)

Disables event with the specified name.

If multiple events with same name (for example, the same class is loaded in different class loaders), then all events that match the name are disabled.

Parameters
name:String

the settings for the event, not null

Returns:EventSettings

an event setting for further configuration, not null

dumpback to summary
public void dump(Path destination) throws IOException

Writes recording data to a file.

The recording stream must be started, but not closed.

It's highly recommended that a max age or max size is set before starting the stream. Otherwise, the dump may not contain any events.

Parameters
destination:Path

the location where recording data is written, not null

Exceptions
IOException:
if the recording data can't be copied to the specified location, or if the stream is closed, or not started.
Since
17
See Also
RemoteRecordingStream#setMaxAge(Duration), RemoteRecordingStream#setMaxSize(long)
enableback to summary
public EventSettings enable(String name)

Enables the event with the specified name.

If multiple events have the same name (for example, the same class is loaded in different class loaders), then all events that match the name are enabled.

Parameters
name:String

the settings for the event, not null

Returns:EventSettings

an event setting for further configuration, not null

See Also
EventType
ensureStartableback to summary
private void ensureStartable()
getRecordingInfoback to summary
private RecordingInfo getRecordingInfo(List<RecordingInfo> infos, long id) throws IOException
isClosedback to summary
pack-priv boolean isClosed()
makeTempDirectoryback to summary
private static Path makeTempDirectory() throws IOException
onCloseback to summary
public void onClose(Runnable action)

Implements jdk.jfr.consumer.EventStream.onClose.

Doc from jdk.jfr.consumer.EventStream.onClose.

Registers an action to perform when the stream is closed.

If the stream is already closed, the action will be performed immediately in the current thread.

Annotations
@Override
onErrorback to summary
public void onError(Consumer<Throwable> action)

Implements jdk.jfr.consumer.EventStream.onError.

Doc from jdk.jfr.consumer.EventStream.onError.

Registers an action to perform if an exception occurs.

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.

Annotations
@Override
onEventback to summary
public void onEvent(Consumer<RecordedEvent> action)

Implements jdk.jfr.consumer.EventStream.onEvent.

Doc from jdk.jfr.consumer.EventStream.onEvent.

Registers an action to perform on all events in the stream.

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.

Annotations
@Override
onEventback to summary
public void onEvent(String eventName, Consumer<RecordedEvent> action)

Implements jdk.jfr.consumer.EventStream.onEvent.

Doc from jdk.jfr.consumer.EventStream.onEvent.

Registers an action to perform on all events matching a name.

Annotations
@Override
onFlushback to summary
public void onFlush(Runnable action)

Implements jdk.jfr.consumer.EventStream.onFlush.

Doc from jdk.jfr.consumer.EventStream.onFlush.

Registers an action to perform after the stream has been flushed.

Annotations
@Override
onMetadataback to summary
public void onMetadata(Consumer<MetadataEvent> action)

Overrides default jdk.jfr.consumer.EventStream.onMetadata.

Doc from jdk.jfr.consumer.EventStream.onMetadata.

Registers an action to perform when new metadata arrives in the stream. The event type of an event always arrives sometime before the actual event. The action must be registered before the stream is started.

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); } }
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);
    }
}
Annotations
@Override
removeback to summary
public boolean remove(Object action)

Implements jdk.jfr.consumer.EventStream.remove.

Doc from jdk.jfr.consumer.EventStream.remove.

Unregisters an action.

If the action has been registered multiple times, all instances are unregistered.

Annotations
@Override
setEndTimeback to summary
public void setEndTime(Instant endTime)

Implements jdk.jfr.consumer.EventStream.setEndTime.

Doc from jdk.jfr.consumer.EventStream.setEndTime.

Specifies the end time of the stream.

The end time must be set before starting the stream.

At end time, the stream is closed.

Annotations
@Override
setMaxAgeback to summary
public void setMaxAge(Duration maxAge)

Determines how far back data is kept for the stream.

To control the amount of recording data stored on disk, the maximum length of time to retain the data can be specified. Data stored on disk that is older than the specified length of time is removed by the Java Virtual Machine (JVM).

If neither maximum limit or the maximum age is set, the size of the recording may grow indefinitely if events are not consumed.

Parameters
maxAge:Duration

the length of time that data is kept, or null if infinite

Exceptions
IllegalArgumentException:
if maxAge is negative
IllegalStateException:
if the recording is in the CLOSED state
setMaxSizeback to summary
public void setMaxSize(long maxSize)

Determines how much data is kept for the stream.

To control the amount of recording data that is stored on disk, the maximum amount of data to retain can be specified. When the maximum limit is exceeded, the Java Virtual Machine (JVM) removes the oldest chunk to make room for a more recent chunk.

If neither maximum limit or the maximum age is set, the size of the recording may grow indefinitely if events are not consumed.

The size is measured in bytes.

Parameters
maxSize:long

the amount of data to retain, 0 if infinite

Exceptions
IllegalArgumentException:
if maxSize is negative
IllegalStateException:
if the recording is in CLOSED state
setOrderedback to summary
public void setOrdered(boolean ordered)

Implements jdk.jfr.consumer.EventStream.setOrdered.

Doc from jdk.jfr.consumer.EventStream.setOrdered.

Specifies that events arrive in chronological order, sorted by the time they were committed to the stream.

Annotations
@Override
setReuseback to summary
public void setReuse(boolean reuse)

Implements jdk.jfr.consumer.EventStream.setReuse.

Doc from jdk.jfr.consumer.EventStream.setReuse.

Specifies that the event object in an 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.

Annotations
@Override
setSettingsback to summary
public void setSettings(Map<String, String> settings)

Replaces all settings for this recording stream.

The following example connects to a remote host and stream events using settings from the "default" configuration.

{
    String host = "com.example";
    int port = 4711;

    String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";

    JMXServiceURL u = new JMXServiceURL(url);
    JMXConnector c = JMXConnectorFactory.connect(u);
    MBeanServerConnection conn = c.getMBeanServerConnection();

    try (final var rs = new RemoteRecordingStream(conn)) {
        rs.onMetadata(e -> {
            for (Configuration c : e.getConfigurations()) {
                if (c.getName().equals("default")) {
                    rs.setSettings(c.getSettings());
                }
            }
        });
        rs.onEvent(System.out::println);
        rs.start();
    }


Parameters
settings:Map<String, String>

the settings to set, not null

See Also
Recording#setSettings(Map)
setStartTimeback to summary
public void setStartTime(Instant startTime)

Implements jdk.jfr.consumer.EventStream.setStartTime.

Doc from jdk.jfr.consumer.EventStream.setStartTime.

Specifies the start time of the stream.

The start time must be set before starting the stream

Annotations
@Override
startback to summary
public void start()

Implements jdk.jfr.consumer.EventStream.start.

Doc from jdk.jfr.consumer.EventStream.start.

Starts processing of actions.

Actions are performed in the current thread.

To stop the stream, use the close() method.

Annotations
@Override
startAsyncback to summary
public void startAsync()

Implements jdk.jfr.consumer.EventStream.startAsync.

Doc from jdk.jfr.consumer.EventStream.startAsync.

Starts asynchronous processing of actions.

Actions are performed in a single separate thread.

To stop the stream, use the close() method.

Annotations
@Override
startDownloadback to summary
private void startDownload()
stopback to summary
public boolean stop()

Stops the recording stream.

Stops a started stream and waits until all events in the recording have been consumed.

Invoking this method in an action, for example in the onEvent(Consumer) method, could block the stream indefinitely. To stop the stream abruptly, use the close method.

The following code snippet illustrates how this method can be used in conjunction with the startAsync() method to monitor what happens during a test method:

AtomicLong bytesWritten = new AtomicLong(); try (var r = new RemoteRecordingStream(connection)) { r.setMaxSize(Long.MAX_VALUE); r.enable("jdk.FileWrite").withoutThreshold(); r.onEvent(event -> bytesWritten.addAndGet(event.getLong("bytesWritten")) ); r.startAsync(); testFoo(); r.stop(); if (bytesWritten.get() > 1_000_000L) { r.dump(Path.of("file-write-events.jfr")); throw new AssertionError("testFoo() writes too much data to disk"); } }
AtomicLong bytesWritten = new AtomicLong();
try (var r = new RemoteRecordingStream(connection)) {
  r.setMaxSize(Long.MAX_VALUE);
  r.enable("jdk.FileWrite").withoutThreshold();
  r.onEvent(event ->
    bytesWritten.addAndGet(event.getLong("bytesWritten"))
  );
  r.startAsync();
  testFoo();
  r.stop();
  if (bytesWritten.get() > 1_000_000L) {
    r.dump(Path.of("file-write-events.jfr"));
    throw new AssertionError("testFoo() writes too much data to disk");
  }
}
Returns:boolean

true if recording is stopped, false otherwise

Exceptions
IllegalStateException:
if the recording is not started or is already stopped
Since
20
updateOnCompleteHandlerback to summary
private void updateOnCompleteHandler()
jdk.management.jfr back to summary

pack-priv final Class RemoteRecordingStream.ChunkConsumer

extends Object
implements Consumer<Long>
Class Inheritance
All Implemented Interfaces
java.util.function.Consumer

Field Summary

Modifier and TypeField and Description
private final DiskRepository

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public void
accept(Long endNanos)

Implements java.util.function.Consumer.accept.

Performs this operation on the given argument.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

repositoryback to summary
private final DiskRepository repository

Constructor Detail

ChunkConsumerback to summary
pack-priv ChunkConsumer(DiskRepository repository)

Method Detail

acceptback to summary
public void accept(Long endNanos)

Implements java.util.function.Consumer.accept.

Doc from java.util.function.Consumer.accept.

Performs this operation on the given argument.

Annotations
@Override
jdk.management.jfr back to summary

pack-priv final Class RemoteRecordingStream.RemoteSettings

extends Object
implements EventSettingsModifier
Class Inheritance
All Implemented Interfaces
jdk.jfr.internal.management.EventSettingsModifier

Field Summary

Modifier and TypeField and Description
private final String
private final FlightRecorderMXBean
private final long

Constructor Summary

AccessConstructor and Description
pack-priv
RemoteSettings(FlightRecorderMXBean mbean, long recordingId, String identifier)

Method Summary

Modifier and TypeMethod and Description
private Map<String, String>
public Map<String, String>
public void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

identifierback to summary
private final String identifier
mbeanback to summary
private final FlightRecorderMXBean mbean
recordingIdback to summary
private final long recordingId

Constructor Detail

RemoteSettingsback to summary
pack-priv RemoteSettings(FlightRecorderMXBean mbean, long recordingId, String identifier)

Method Detail

getEventSettingsback to summary
private Map<String, String> getEventSettings()
toMapback to summary
public Map<String, String> toMap()

Implements jdk.jfr.internal.management.EventSettingsModifier.toMap.

Annotations
@Override
withback to summary
public void with(String name, String value)

Implements jdk.jfr.internal.management.EventSettingsModifier.with.

Annotations
@Override