1+ import java .time .Duration ;
2+ import java .util .stream .IntStream ;
3+ import java .util .ArrayList ;
4+
5+ import jdk .jfr .consumer .RecordingStream ;
6+
7+ /***
8+ * The profiles configurations is stored in: `$JAVA_HOME/lib/jrf/`
9+ */
10+ public class JFREventStreamTest {
11+ public static void main (String [] args ) throws InterruptedException {
12+ var task = new FibonacciCalculator (Thread .currentThread ());
13+
14+ var thread = new Thread (task , "t-fib" );
15+ thread .start ();
16+
17+ try (var rs = new RecordingStream ()) {
18+ rs .enable ("jdk.CPULoad" ).withPeriod (Duration .ofSeconds (1 ));
19+ rs .enable ("jdk.GarbageCollection" ).withPeriod (Duration .ofSeconds (1 ));
20+ rs .enable ("jdk.GCHeapSummary" ).withPeriod (Duration .ofSeconds (1 ));
21+
22+ rs .onEvent ("jdk.CPULoad" , event -> {
23+ System .out .printf ("\t CPU load: %f%% - %f%%%n" ,
24+ (event .getFloat ("jvmUser" ) * 100 ),
25+ (event .getFloat ("machineTotal" ) * 100 )
26+ );
27+ });
28+ rs .onEvent ("jdk.GCHeapSummary" , event -> {
29+ System .out .printf ("\t GC - Summary - %s %f MB%n" ,
30+ event .getString ("when" ),
31+ (event .getFloat ("heapUsed" ) / 1_000_000 )
32+ );
33+
34+ });
35+ rs .onEvent ("jdk.GarbageCollection" , event -> {
36+ System .out .printf ("\t GC - Cause %s - Durantion: %.04fms%n" , event .getString ("cause" ), (event .getFloat ("duration" ) / 1_000_000 ));
37+ });
38+ rs .startAsync ();
39+
40+ thread .join ();
41+ }
42+
43+ }
44+ }
45+
46+ class FibonacciCalculator implements Runnable {
47+ private Thread thread ;
48+
49+ FibonacciCalculator (Thread thread ) {
50+ this .thread = thread ;
51+ }
52+
53+ public void run () {
54+ System .out .println ("Starting calculation" );
55+ int number = 40 ;
56+ while (true ) {
57+ System .out .println ("Calculating for " + number );
58+ var result = calculate (number );
59+ System .out .println ("Result for " + number + " is " + result );
60+ if (!thread .isAlive ()) {
61+ System .out .println ("Ending calculation" );
62+ break ;
63+ }
64+
65+ number += 5 ;
66+ }
67+ }
68+
69+ /**
70+ * Bad implementation to take much time.
71+ */
72+ public long calculate (int n ) {
73+ if (n <= 1 )
74+ return 1 ;
75+ var list = new ArrayList <>(n );
76+ IntStream .range (0 , n ).forEach (__ -> list .add (new Object ()));
77+ return calculate (n - 1 ) + calculate (n - 2 );
78+ }
79+ }
0 commit comments