20 外部プロセスからのイベント・ストリームの作成

サンプルStreamExternalEventsWithAttachAPISample.javaでは、別のJavaプロセスであるサンプルのSleepOneSecondIntervals.javaからイベント・ストリームが作成されます。

SleepOneSecondIntervalsは、1秒間隔で繰り返しスリープ状態になります。「プロセスにおけるイベント・ストリームの作成(アクティブ)」で説明されているように、Thread.sleep()が呼び出されるたびに、jdk.ThreadSleepイベントが発生します。

public class SleepOneSecondIntervals {

    public static void main(String... args) throws Exception {
        long pid = ProcessHandle.current().pid();
        System.out.println("Process ID: " + pid);
        while(true) {
            System.out.println("Sleeping for 1s...");
            Thread.sleep(1000);
        }
    }
}

StreamExternalEventsWithAttachAPISampleはアタッチAPIを使用して、SleepOneSecondIntervalsが実行されている仮想マシンを取得します。StreamExternalEventsWithAttachAPISampleはこの仮想マシンから、jdk.jfr.repositoryプロパティを介して、そのFlight Recorderのリポジトリの場所を取得します。次に、EventStream::openRepository(Paths)メソッドを介し、このリポジトリを使用してEventStreamが作成されます。

import java.nio.file.Paths;
import java.util.Optional;
import java.util.Properties;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

import jdk.jfr.consumer.EventStream;

public class StreamExternalEventsWithAttachAPISample {
    public static void main(String... args) throws Exception {

        Optional<VirtualMachineDescriptor> vmd =
            VirtualMachine.list().stream()
            .filter(v -> v.displayName()
                .contains("SleepOneSecondIntervals"))
            .findFirst();

        if (vmd.isEmpty()) {
            throw new RuntimeException("Cannot find VM for SleepOneSecondIntervals");
        }

        VirtualMachine vm = VirtualMachine.attach(vmd.get());

        // Get system properties from attached VM

        Properties props = vm.getSystemProperties();
        String repository = props.getProperty("jdk.jfr.repository");
        System.out.println("jdk.jfr.repository: " + repository);

        try (EventStream es = EventStream
            .openRepository(Paths.get(repository))) {
            System.out.println("Found repository ...");
            es.onEvent("jdk.ThreadSleep", System.out::println);
            es.start();
        }
    }
}

SleepOneSecondIntervals.javaStreamExternalEventsWithAttachAPISample.javaをコンパイルします。その後、次のコマンドでSleepOneSecondIntervalsを実行します:

java -XX:StartFlightRecording SleepOneSecondIntervals

新しいコマンド・シェルで、StreamExternalEventsWithAttachAPISampleを実行します:

java StreamExternalEventsWithAttachAPISample

次のような出力が表示されます:

jdk.jfr.repository: C:\Users\<your user name>\AppData\Local\Temp\2019_12_08_23_32_47_5100
Found repository ...
jdk.ThreadSleep {
  startTime = 00:15:31.643
  duration = 1.04 s
  time = 1.00 s
  eventThread = "main" (javaThreadId = 1)
  stackTrace = [
    java.lang.Thread.sleep(long)
    SleepOneSecondIntervals.main(String[]) line: 8
  ]
}

jdk.ThreadSleep {
  startTime = 00:15:32.689
  duration = 1.05 s
  time = 1.00 s
  eventThread = "main" (javaThreadId = 1)
  stackTrace = [
    java.lang.Thread.sleep(long)
    SleepOneSecondIntervals.main(String[]) line: 8
  ]
}
...

サンプルStreamExternalEventsWithJcmdSample.javaは、アタッチAPIを使用してSleepOneSecondIntervalsのFlight Recorderを開始する点を除き、StreamExternalEventsWithAttachAPISampleに似ています。このAPIを使用して、サンプルでは、PIDがSleepOneSecondIntervalsのコマンドjcmd <PID> JFR.startが実行されます:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.Properties;

import com.sun.tools.attach.VirtualMachine;

import jdk.jfr.consumer.EventStream;

public class StreamExternalEventsWithJcmdSample {
    public static void main(String... args) throws Exception {
        if (args[0] == null) {
            System.err.println("Requires PID of process as argument");
            System.exit(1);
        }

        String pid = args[0];

        Process p = Runtime.getRuntime().exec(
            "jcmd " + pid + " JFR.start");

        printOutput(p);

        // Wait for jcmd to start the recording
        Thread.sleep(1000);

        VirtualMachine vm = VirtualMachine.attach(pid);
        Properties props = vm.getSystemProperties();
        String repository = props.getProperty("jdk.jfr.repository");
        System.out.println("jdk.jfr.repository: " + repository);

        try (EventStream es = EventStream
            .openRepository(Paths.get(repository))) {
            System.out.println("Found repository ...");
            es.onEvent("jdk.ThreadSleep", System.out::println);
            es.start();
        }
    }

    private static void printOutput(Process proc) throws IOException {
        BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(proc.getInputStream()));

        BufferedReader stdError = new BufferedReader(
            new InputStreamReader(proc.getErrorStream()));

        // Read the output from the command
        System.out.println(
            "Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // Read any errors from the attempted command
        System.out.println(
            "Here is the standard error of the " + "command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    }
}

SleepOneSecondIntervals.javaStreamExternalEventsWithJcmdSample.javaをコンパイルします。その後、次のコマンドでSleepOneSecondIntervalsを実行します:

java -XX:StartFlightRecording SleepOneSecondIntervals

次のような出力が表示されます:

Started recording 1. No limit specified, using maxsize=250MB as default.

Use jcmd 5100 JFR.dump name=1 filename=FILEPATH to copy recording data to file.
Process ID: 5100
Sleeping for 1s...
Sleeping for 1s...
Sleeping for 1s...
...

SleepOneSecondIntervalsのPIDをメモします(この例では5100です)。このサンプルの実行中に、新しいコマンド・シェルで、次のコマンドを使用してStreamExternalEventsWithJcmdSampleを実行します

java StreamExternalEventsWithJcmdSample <PID of SleepOneSecondIntervals>

StreamExternalEventsWithAttachAPISampleのような出力が表示されます。