Skip to content

Commit a6bf843

Browse files
author
duke
committedFeb 7, 2022
Automatic merge of jdk:master into master
2 parents ba76bbb + 2f71a6b commit a6bf843

15 files changed

+487
-299
lines changed
 

‎src/jdk.jfr/share/classes/jdk/jfr/AnnotationElement.java

+1-16
Original file line numberDiff line numberDiff line change
@@ -46,22 +46,7 @@
4646
* <p>
4747
* The following example shows how {@code AnnotationElement} can be used to dynamically define events.
4848
*
49-
* <pre>{@literal
50-
* List<AnnotationElement> typeAnnotations = new ArrayList<>();
51-
* typeAnnotations.add(new AnnotationElement(Name.class, "com.example.HelloWorld"));
52-
* typeAnnotations.add(new AnnotationElement(Label.class, "Hello World"));
53-
* typeAnnotations.add(new AnnotationElement(Description.class, "Helps programmer getting started"));
54-
*
55-
* List<AnnotationElement> fieldAnnotations = new ArrayList<>();
56-
* fieldAnnotations.add(new AnnotationElement(Label.class, "Message"));
57-
*
58-
* List<ValueDescriptor> fields = new ArrayList<>();
59-
* fields.add(new ValueDescriptor(String.class, "message", fieldAnnotations));
60-
*
61-
* EventFactory f = EventFactory.create(typeAnnotations, fields);
62-
* Event event = f.newEvent();
63-
* event.commit();
64-
* }</pre>
49+
* {@snippet class="Snippets" region="AnnotationElementOverview"}
6550
*
6651
* @since 9
6752
*/

‎src/jdk.jfr/share/classes/jdk/jfr/Event.java

+1-21
Original file line numberDiff line numberDiff line change
@@ -31,27 +31,7 @@
3131
* <p>
3232
* The following example shows how to implement an {@code Event} class.
3333
*
34-
* <pre>{@literal
35-
* import jdk.jfr.Event;
36-
* import jdk.jfr.Description;
37-
* import jdk.jfr.Label;
38-
*
39-
* public class Example {
40-
*
41-
* @Label("Hello World")
42-
* @Description("Helps programmer getting started")
43-
* static class HelloWorld extends Event {
44-
* @Label("Message")
45-
* String message;
46-
* }
47-
*
48-
* public static void main(String... args) {
49-
* HelloWorld event = new HelloWorld();
50-
* event.message = "hello, world!";
51-
* event.commit();
52-
* }
53-
* }
54-
* }</pre>
34+
* {@snippet class="Snippets" region="EventOverview"}
5535
* <p>
5636
* After an event is allocated and its field members are populated, it can be
5737
* written to the Flight Recorder system by using the {@link #commit()} method.

‎src/jdk.jfr/share/classes/jdk/jfr/EventFactory.java

+1-23
Original file line numberDiff line numberDiff line change
@@ -52,29 +52,7 @@
5252
* <p>
5353
* The following example shows how to implement a dynamic {@code Event} class.
5454
*
55-
* <pre>
56-
* {@code
57-
* List<ValueDescriptor> fields = new ArrayList<>();
58-
* List<AnnotationElement> messageAnnotations = Collections.singletonList(new AnnotationElement(Label.class, "Message"));
59-
* fields.add(new ValueDescriptor(String.class, "message", messageAnnotations));
60-
* List<AnnotationElement> numberAnnotations = Collections.singletonList(new AnnotationElement(Label.class, "Number"));
61-
* fields.add(new ValueDescriptor(int.class, "number", numberAnnotations));
62-
*
63-
* String[] category = { "Example", "Getting Started" };
64-
* List<AnnotationElement> eventAnnotations = new ArrayList<>();
65-
* eventAnnotations.add(new AnnotationElement(Name.class, "com.example.HelloWorld"));
66-
* eventAnnotations.add(new AnnotationElement(Label.class, "Hello World"));
67-
* eventAnnotations.add(new AnnotationElement(Description.class, "Helps programmer getting started"));
68-
* eventAnnotations.add(new AnnotationElement(Category.class, category));
69-
*
70-
* EventFactory f = EventFactory.create(eventAnnotations, fields);
71-
*
72-
* Event event = f.newEvent();
73-
* event.set(0, "hello, world!");
74-
* event.set(1, 4711);
75-
* event.commit();
76-
* }
77-
* </pre>
55+
* {@snippet class="Snippets" region="EventFactoryOverview"}
7856
*
7957
* @since 9
8058
*/

‎src/jdk.jfr/share/classes/jdk/jfr/EventSettings.java

+2-14
Original file line numberDiff line numberDiff line change
@@ -38,21 +38,9 @@
3838
* chaining.
3939
* <p>
4040
* The following example shows how to use the {@code EventSettings} class.
41-
* <pre>
42-
* {@code
43-
* Recording r = new Recording();
44-
* r.enable("jdk.CPULoad")
45-
* .withPeriod(Duration.ofSeconds(1));
46-
* r.enable("jdk.FileWrite")
47-
* .withoutStackTrace()
48-
* .withThreshold(Duration.ofNanos(10));
49-
* r.start();
50-
* Thread.sleep(10_000);
51-
* r.stop();
52-
* r.dump(Files.createTempFile("recording", ".jfr"));
5341
*
54-
* }
55-
* </pre>
42+
* {@snippet class="Snippets" region="EventSettingOverview"}
43+
*
5644
* @since 9
5745
*/
5846
public abstract class EventSettings {

‎src/jdk.jfr/share/classes/jdk/jfr/FlightRecorder.java

+1-9
Original file line numberDiff line numberDiff line change
@@ -92,15 +92,7 @@ public List<Recording> getRecordings() {
9292
* <p>
9393
* The following example shows how to create a snapshot and write a subset of the data to a file.
9494
*
95-
* <pre>{@literal
96-
* try (Recording snapshot = FlightRecorder.getFlightRecorder().takeSnapshot()) {
97-
* if (snapshot.getSize() > 0) {
98-
* snapshot.setMaxSize(100_000_000);
99-
* snapshot.setMaxAge(Duration.ofMinutes(5));
100-
* snapshot.dump(Paths.get("snapshot.jfr"));
101-
* }
102-
* }
103-
* }</pre>
95+
* {@snippet class="Snippets" region="FlightRecorderTakeSnapshot"}
10496
*
10597
* The caller must close the recording when access to the data is no longer
10698
* needed.

‎src/jdk.jfr/share/classes/jdk/jfr/MetadataDefinition.java

+1-30
Original file line numberDiff line numberDiff line change
@@ -36,36 +36,7 @@
3636
* In the following example, a transaction event is defined with two
3737
* user-defined annotations, {@code @Severity} and {@code @TransactionId}.
3838
*
39-
* <pre>{@literal
40-
* @MetadataDefinition
41-
* @Label("Severity")
42-
* @Description("Value between 0 and 100 that indicates severity. 100 is most severe.")
43-
* @Retention(RetentionPolicy.RUNTIME)
44-
* @Target({ElementType.TYPE})
45-
* public @interface Severity {
46-
* int value() default 50;
47-
* }
48-
*
49-
* @MetadataDefinition
50-
* @Label("Transaction Id")
51-
* @Relational
52-
* @Retention(RetentionPolicy.RUNTIME)
53-
* @Target({ElementType.FIELD})
54-
* public @interface TransactionId {
55-
* }
56-
*
57-
* @Severity(80)
58-
* @Label("Transaction Blocked")
59-
* class TransactionBlocked extends Event {
60-
* @TransactionId
61-
* @Label("Transaction")
62-
* long transactionId1;
63-
*
64-
* @TransactionId
65-
* @Label("Transaction Blocker")
66-
* long transactionId2;
67-
* }
68-
* }</pre>
39+
* {@snippet class="Snippets" region="MetadataDefinitionOverview"}
6940
*
7041
* Adding {@code @MetadataDefinition} to the declaration of {@code @Severity} and {@code @TransactionId}
7142
* ensures the information is saved by Flight Recorder.

‎src/jdk.jfr/share/classes/jdk/jfr/Recording.java

+7-15
Original file line numberDiff line numberDiff line change
@@ -46,15 +46,7 @@
4646
* <p>
4747
* The following example shows how configure, start, stop and dump recording data to disk.
4848
*
49-
* <pre>{@literal
50-
* Configuration c = Configuration.getConfiguration("default");
51-
* Recording r = new Recording(c);
52-
* r.start();
53-
* System.gc();
54-
* Thread.sleep(5000);
55-
* r.stop();
56-
* r.dump(Files.createTempFile("my-recording", ".jfr"));
57-
* }</pre>
49+
* {@snippet class="Snippets" region="RecordingOverview"}
5850
*
5951
* @since 9
6052
*/
@@ -143,9 +135,9 @@ public Recording() {
143135
* <p>
144136
* The following example shows how create a recording that uses a predefined configuration.
145137
*
146-
* <pre>{@literal
138+
* {@snippet :
147139
* Recording r = new Recording(Configuration.getConfiguration("default"));
148-
* }</pre>
140+
* }
149141
*
150142
* The newly created recording is in the {@link RecordingState#NEW} state. To
151143
* start the recording, invoke the {@link Recording#start()} method.
@@ -307,21 +299,21 @@ public String getName() {
307299
* <p>
308300
* The following example shows how to set event settings for a recording.
309301
*
310-
* <pre>{@literal
302+
* {@snippet :
311303
* Map<String, String> settings = new HashMap<>();
312304
* settings.putAll(EventSettings.enabled("jdk.CPUSample").withPeriod(Duration.ofSeconds(2)).toMap());
313305
* settings.putAll(EventSettings.enabled(MyEvent.class).withThreshold(Duration.ofSeconds(2)).withoutStackTrace().toMap());
314306
* settings.put("jdk.ExecutionSample#period", "10 ms");
315307
* recording.setSettings(settings);
316-
* }</pre>
308+
* }
317309
*
318310
* The following example shows how to merge settings.
319311
*
320-
* <pre>{@literal
312+
* {@snippet :
321313
* Map<String, String> settings = recording.getSettings();
322314
* settings.putAll(additionalSettings);
323315
* recording.setSettings(settings);
324-
* }</pre>
316+
* }
325317
*
326318
* @param settings the settings to set, not {@code null}
327319
*/

‎src/jdk.jfr/share/classes/jdk/jfr/SettingControl.java

+3-68
Original file line numberDiff line numberDiff line change
@@ -37,30 +37,7 @@
3737
* The following example shows a naive implementation of a setting control for
3838
* regular expressions:
3939
*
40-
* <pre>{@literal
41-
* final class RegExpControl extends SettingControl {
42-
* private Pattern pattern = Pattern.compile(".*");
43-
*
44-
* @Override
45-
* public void setValue(String value) {
46-
* this.pattern = Pattern.compile(value);
47-
* }
48-
*
49-
* @Override
50-
* public String combine(Set<String> values) {
51-
* return String.join("|", values);
52-
* }
53-
*
54-
* @Override
55-
* public String getValue() {
56-
* return pattern.toString();
57-
* }
58-
*
59-
* public boolean matches(String s) {
60-
* return pattern.matcher(s).find();
61-
* }
62-
* }
63-
* }</pre>
40+
* {@snippet class="Snippets" region="SettingControlOverview1"}
6441
*
6542
* The {@code setValue(String)}, {@code getValue()} and
6643
* {@code combine(Set<String>)} methods are invoked when a setting value
@@ -85,55 +62,13 @@
8562
* The following example shows how to create an event that uses the
8663
* regular expression filter defined above.
8764
*
88-
* <pre>{@literal
89-
* abstract class HTTPRequest extends Event {
90-
* @Label("Request URI")
91-
* protected String uri;
92-
*
93-
* @Label("Servlet URI Filter")
94-
* @SettingDefinition
95-
* protected boolean uriFilter(RegExpControl regExp) {
96-
* return regExp.matches(uri);
97-
* }
98-
* }
99-
*
100-
* @Label("HTTP Get Request")
101-
* class HTTPGetRequest extends HTTPRequest {
102-
* }
103-
*
104-
* @Label("HTTP Post Request")
105-
* class HTTPPostRequest extends HTTPRequest {
106-
* }
107-
*
108-
* class ExampleServlet extends HttpServlet {
109-
* protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
110-
* HTTPGetRequest request = new HTTPGetRequest();
111-
* request.begin();
112-
* request.uri = req.getRequestURI();
113-
* ...
114-
* request.commit();
115-
* }
116-
*
117-
* protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
118-
* HTTPPostRequest request = new HTTPPostRequest();
119-
* request.begin();
120-
* request.uri = req.getRequestURI();
121-
* ...
122-
* request.commit();
123-
* }
124-
* }
125-
* }</pre>
65+
* {@snippet class="Snippets" region="SettingControlOverview2"}
12666
*
12767
* <p>
12868
* The following example shows how an event can be filtered by assigning the
12969
* {@code "uriFilter"} setting with the specified regular expressions.
13070
*
131-
* <pre>{@literal
132-
* Recording r = new Recording();
133-
* r.enable("HTTPGetRequest").with("uriFilter", "https://www.example.com/list/.*");
134-
* r.enable("HTTPPostRequest").with("uriFilter", "https://www.example.com/login/.*");
135-
* r.start();
136-
* }</pre>
71+
* {@snippet class="Snippets" region="SettingControlOverview3"}
13772
*
13873
* @see SettingDefinition
13974
*

‎src/jdk.jfr/share/classes/jdk/jfr/consumer/EventStream.java

+1-19
Original file line numberDiff line numberDiff line change
@@ -95,25 +95,7 @@
9595
* The following example shows how an {@code EventStream} can be used to listen
9696
* to events on a JVM running Flight Recorder
9797
*
98-
* <pre>{@literal
99-
* try (var es = EventStream.openRepository()) {
100-
* es.onEvent("jdk.CPULoad", event -> {
101-
* System.out.println("CPU Load " + event.getEndTime());
102-
* System.out.println(" Machine total: " + 100 * event.getFloat("machineTotal") + "%");
103-
* System.out.println(" JVM User: " + 100 * event.getFloat("jvmUser") + "%");
104-
* System.out.println(" JVM System: " + 100 * event.getFloat("jvmSystem") + "%");
105-
* System.out.println();
106-
* });
107-
* es.onEvent("jdk.GarbageCollection", event -> {
108-
* System.out.println("Garbage collection: " + event.getLong("gcId"));
109-
* System.out.println(" Cause: " + event.getString("cause"));
110-
* System.out.println(" Total pause: " + event.getDuration("sumOfPauses"));
111-
* System.out.println(" Longest pause: " + event.getDuration("longestPause"));
112-
* System.out.println();
113-
* });
114-
* es.start();
115-
* }
116-
* }</pre>
98+
* {@snippet class="Snippets" region="EventStreamOverview"}
11799
* <p>
118100
* To start recording together with the stream, see {@link RecordingStream}.
119101
*

‎src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordedObject.java

+1-17
Original file line numberDiff line numberDiff line change
@@ -225,23 +225,7 @@ public boolean hasField(String name) {
225225
* for callers of this method is to validate the field before attempting access.
226226
* <p>
227227
* Example
228-
*
229-
* <pre>{@literal
230-
* if (event.hasField("intValue")) {
231-
* int intValue = event.getValue("intValue");
232-
* System.out.println("Int value: " + intValue);
233-
* }
234-
*
235-
* if (event.hasField("objectClass")) {
236-
* RecordedClass clazz = event.getValue("objectClass");
237-
* System.out.println("Class name: " + clazz.getName());
238-
* }
239-
*
240-
* if (event.hasField("sampledThread")) {
241-
* RecordedThread sampledThread = event.getValue("sampledThread");
242-
* System.out.println("Sampled thread: " + sampledThread.getJavaName());
243-
* }
244-
* }</pre>
228+
* {@snippet class="Snippets" region="RecordedObjectGetValue"}
245229
*
246230
* @param <T> the return type
247231
* @param name of the field to get, not {@code null}

‎src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordingFile.java

+1-8
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,7 @@
4949
* <p>
5050
* The following example shows how read and print all events in a recording file.
5151
*
52-
* <pre>{@literal
53-
* try (RecordingFile recordingFile = new RecordingFile(Paths.get("recording.jfr"))) {
54-
* while (recordingFile.hasMoreEvents()) {
55-
* RecordedEvent event = recordingFile.readEvent();
56-
* System.out.println(event);
57-
* }
58-
* }
59-
* }</pre>
52+
* {@snippet class="Snippets" region="RecordingFileOverview"}
6053
*
6154
* @since 9
6255
*/

‎src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordingStream.java

+6-37
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,8 @@
5656
* The following example shows how to record events using the default
5757
* configuration and print the Garbage Collection, CPU Load and JVM Information
5858
* event to standard out.
59-
* <pre>{@literal
60-
* Configuration c = Configuration.getConfiguration("default");
61-
* try (var rs = new RecordingStream(c)) {
62-
* rs.onEvent("jdk.GarbageCollection", System.out::println);
63-
* rs.onEvent("jdk.CPULoad", System.out::println);
64-
* rs.onEvent("jdk.JVMInformation", System.out::println);
65-
* rs.start();
66-
* }
67-
* }</pre>
59+
*
60+
* {@snippet class="Snippets" region="RecordingStreamOverview"}
6861
*
6962
* @since 14
7063
*/
@@ -140,13 +133,7 @@ private List<Configuration> configurations() {
140133
* The following example shows how to create a recording stream that uses a
141134
* predefined configuration.
142135
*
143-
* <pre>{@literal
144-
* var c = Configuration.getConfiguration("default");
145-
* try (var rs = new RecordingStream(c)) {
146-
* rs.onEvent(System.out::println);
147-
* rs.start();
148-
* }
149-
* }</pre>
136+
* {@snippet class="Snippets" region="RecordingStreamConstructor"}
150137
*
151138
* @param configuration configuration that contains the settings to use,
152139
* not {@code null}
@@ -189,17 +176,7 @@ public EventSettings enable(String name) {
189176
* The following example records 20 seconds using the "default" configuration
190177
* and then changes settings to the "profile" configuration.
191178
*
192-
* <pre>{@literal
193-
* Configuration defaultConfiguration = Configuration.getConfiguration("default");
194-
* Configuration profileConfiguration = Configuration.getConfiguration("profile");
195-
* try (var rs = new RecordingStream(defaultConfiguration)) {
196-
* rs.onEvent(System.out::println);
197-
* rs.startAsync();
198-
* Thread.sleep(20_000);
199-
* rs.setSettings(profileConfiguration.getSettings());
200-
* Thread.sleep(20_000);
201-
* }
202-
* }</pre>
179+
* {@snippet class="Snippets" region="RecordingStreamSetSettings"}
203180
*
204181
* @param settings the settings to set, not {@code null}
205182
*
@@ -384,16 +361,8 @@ public void start() {
384361
* The following example prints the CPU usage for ten seconds. When
385362
* the current thread leaves the try-with-resources block the
386363
* stream is stopped/closed.
387-
* <pre>{@literal
388-
* try (var stream = new RecordingStream()) {
389-
* stream.enable("jdk.CPULoad").withPeriod(Duration.ofSeconds(1));
390-
* stream.onEvent("jdk.CPULoad", event -> {
391-
* System.out.println(event);
392-
* });
393-
* stream.startAsync();
394-
* Thread.sleep(10_000);
395-
* }
396-
* }</pre>
364+
*
365+
* {@snippet class="Snippets" region="RecordingStreamStartAsync"}
397366
*
398367
* @throws IllegalStateException if the stream is already started or closed
399368
*/

‎src/jdk.jfr/share/classes/jdk/jfr/consumer/package-info.java

+1-22
Original file line numberDiff line numberDiff line change
@@ -27,29 +27,8 @@
2727
* This package contains classes for consuming Flight Recorder data.
2828
* <p>
2929
* In the following example, the program prints a histogram of all method samples in a recording.
30-
* <pre>{@literal
31-
* public static void main(String[] args) throws IOException {
32-
* if (args.length != 1) {
33-
* System.err.println("Must specify a recording file.");
34-
* return;
35-
* }
3630
*
37-
* RecordingFile.readAllEvents(Path.of(args[0])).stream()
38-
* .filter(e -> e.getEventType().getName().equals("jdk.ExecutionSample"))
39-
* .map(e -> e.getStackTrace())
40-
* .filter(s -> s != null)
41-
* .map(s -> s.getFrames().get(0))
42-
* .filter(f -> f.isJavaFrame())
43-
* .map(f -> f.getMethod())
44-
* .collect(
45-
* Collectors.groupingBy(m -> m.getType().getName() + "." + m.getName() + " " + m.getDescriptor(),
46-
* Collectors.counting()))
47-
* .entrySet()
48-
* .stream()
49-
* .sorted((a, b) -> b.getValue().compareTo(a.getValue()))
50-
* .forEach(e -> System.out.printf("%8d %s\n", e.getValue(), e.getKey()));
51-
* }
52-
* }</pre>
31+
* {@snippet class="Snippets" region="PackageOverview"}
5332
* <p>
5433
* <b>Null-handling</b>
5534
* <p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
/*
2+
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation. Oracle designates this
8+
* particular file as subject to the "Classpath" exception as provided
9+
* by Oracle in the LICENSE file that accompanied this code.
10+
*
11+
* This code is distributed in the hope that it will be useful, but WITHOUT
12+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14+
* version 2 for more details (a copy is included in the LICENSE file that
15+
* accompanied this code).
16+
*
17+
* You should have received a copy of the GNU General Public License version
18+
* 2 along with this work; if not, write to the Free Software Foundation,
19+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20+
*
21+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22+
* or visit www.oracle.com if you need additional information or have any
23+
* questions.
24+
*/
25+
package example2;
26+
27+
import java.io.IOException;
28+
import java.nio.file.Path;
29+
import java.nio.file.Paths;
30+
import java.time.Duration;
31+
import java.util.stream.Collectors;
32+
import jdk.jfr.consumer.EventStream;
33+
import jdk.jfr.consumer.RecordingFile;
34+
import jdk.jfr.consumer.RecordedClass;
35+
import jdk.jfr.consumer.RecordedThread;
36+
import jdk.jfr.consumer.RecordingStream;
37+
import jdk.jfr.Configuration;
38+
import jdk.jfr.consumer.RecordedEvent;
39+
40+
public class Snippets {
41+
42+
class PackageOveriview {
43+
// @start region="PackageOverview"
44+
public static void main(String[] args) throws IOException {
45+
if (args.length != 1) {
46+
System.err.println("Must specify a recording file.");
47+
return;
48+
}
49+
50+
RecordingFile.readAllEvents(Path.of(args[0])).stream()
51+
.filter(e -> e.getEventType().getName().equals("jdk.ExecutionSample"))
52+
.map(e -> e.getStackTrace())
53+
.filter(s -> s != null)
54+
.map(s -> s.getFrames().get(0))
55+
.filter(f -> f.isJavaFrame())
56+
.map(f -> f.getMethod())
57+
.collect(
58+
Collectors.groupingBy(m -> m.getType().getName() + "." + m.getName() + " " + m.getDescriptor(),
59+
Collectors.counting()))
60+
.entrySet()
61+
.stream()
62+
.sorted((a, b) -> b.getValue().compareTo(a.getValue()))
63+
.forEach(e -> System.out.printf("%8d %s\n", e.getValue(), e.getKey()));
64+
}
65+
// @end
66+
}
67+
68+
void EventStreamOverview() throws Exception {
69+
// @start region="EventStreamOverview"
70+
try (var es = EventStream.openRepository()) {
71+
es.onEvent("jdk.CPULoad", event -> {
72+
System.out.println("CPU Load " + event.getEndTime());
73+
System.out.println(" Machine total: " + 100 * event.getFloat("machineTotal") + "%");
74+
System.out.println(" JVM User: " + 100 * event.getFloat("jvmUser") + "%");
75+
System.out.println(" JVM System: " + 100 * event.getFloat("jvmSystem") + "%");
76+
System.out.println();
77+
});
78+
es.onEvent("jdk.GarbageCollection", event -> {
79+
System.out.println("Garbage collection: " + event.getLong("gcId"));
80+
System.out.println(" Cause: " + event.getString("cause"));
81+
System.out.println(" Total pause: " + event.getDuration("sumOfPauses"));
82+
System.out.println(" Longest pause: " + event.getDuration("longestPause"));
83+
System.out.println();
84+
});
85+
es.start();
86+
}
87+
// @end
88+
}
89+
90+
void RecordingFileOverview() throws Exception {
91+
// @start region="RecordingFileOverview"
92+
try (RecordingFile recordingFile = new RecordingFile(Paths.get("recording.jfr"))) {
93+
while (recordingFile.hasMoreEvents()) {
94+
RecordedEvent event = recordingFile.readEvent();
95+
System.out.println(event);
96+
}
97+
}
98+
// @end
99+
}
100+
101+
void RecordedObjectGetValue() {
102+
RecordedEvent event = null;
103+
// @start region="RecordedObjectGetValue"
104+
if (event.hasField("intValue")) {
105+
int intValue = event.getValue("intValue");
106+
System.out.println("Int value: " + intValue);
107+
}
108+
109+
if (event.hasField("objectClass")) {
110+
RecordedClass clazz = event.getValue("objectClass");
111+
System.out.println("Class name: " + clazz.getName());
112+
}
113+
114+
if (event.hasField("sampledThread")) {
115+
RecordedThread sampledThread = event.getValue("sampledThread");
116+
System.out.println("Sampled thread: " + sampledThread.getJavaName());
117+
}
118+
// @end
119+
}
120+
121+
void RecordingStreamOverview() throws Exception {
122+
// @start region="RecordingStreamOverview"
123+
Configuration c = Configuration.getConfiguration("default");
124+
try (var rs = new RecordingStream(c)) {
125+
rs.onEvent("jdk.GarbageCollection", System.out::println);
126+
rs.onEvent("jdk.CPULoad", System.out::println);
127+
rs.onEvent("jdk.JVMInformation", System.out::println);
128+
rs.start();
129+
}
130+
// @end
131+
}
132+
133+
void RecordingStreamConstructor() throws Exception {
134+
// @start region="RecordingStreamConstructor"
135+
var c = Configuration.getConfiguration("default");
136+
try (var rs = new RecordingStream(c)) {
137+
rs.onEvent(System.out::println);
138+
rs.start();
139+
}
140+
// @end
141+
}
142+
143+
void RecordingStreamSetSettings() throws Exception {
144+
// @start region="RecordingStreamSetSettings"
145+
Configuration defaultConfiguration = Configuration.getConfiguration("default");
146+
Configuration profileConfiguration = Configuration.getConfiguration("profile");
147+
try (var rs = new RecordingStream(defaultConfiguration)) {
148+
rs.onEvent(System.out::println);
149+
rs.startAsync();
150+
Thread.sleep(20_000);
151+
rs.setSettings(profileConfiguration.getSettings());
152+
Thread.sleep(20_000);
153+
}
154+
// @end
155+
}
156+
157+
void RecordingStreamStartAsync() throws Exception {
158+
// @start region="RecordingStreamStartAsync"
159+
try (var stream = new RecordingStream()) {
160+
stream.enable("jdk.CPULoad").withPeriod(Duration.ofSeconds(1));
161+
stream.onEvent("jdk.CPULoad", event -> {
162+
System.out.println(event);
163+
});
164+
stream.startAsync();
165+
Thread.sleep(10_000);
166+
}
167+
// @end
168+
}
169+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
/*
2+
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation. Oracle designates this
8+
* particular file as subject to the "Classpath" exception as provided
9+
* by Oracle in the LICENSE file that accompanied this code.
10+
*
11+
* This code is distributed in the hope that it will be useful, but WITHOUT
12+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14+
* version 2 for more details (a copy is included in the LICENSE file that
15+
* accompanied this code).
16+
*
17+
* You should have received a copy of the GNU General Public License version
18+
* 2 along with this work; if not, write to the Free Software Foundation,
19+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20+
*
21+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22+
* or visit www.oracle.com if you need additional information or have any
23+
* questions.
24+
*/
25+
package example1;
26+
27+
import jdk.jfr.AnnotationElement;
28+
import jdk.jfr.ValueDescriptor;
29+
import jdk.jfr.EventFactory;
30+
import jdk.jfr.Event;
31+
import jdk.jfr.Name;
32+
import jdk.jfr.Label;
33+
import jdk.jfr.Description;
34+
import jdk.jfr.Category;
35+
import jdk.jfr.Recording;
36+
import jdk.jfr.MetadataDefinition;
37+
import jdk.jfr.Relational;
38+
import jdk.jfr.consumer.RecordingFile;
39+
import jdk.jfr.Configuration;
40+
import jdk.jfr.SettingDefinition;
41+
import jdk.jfr.SettingControl;
42+
import jdk.jfr.FlightRecorder;
43+
44+
import java.io.IOException;
45+
import java.nio.file.Files;
46+
import java.nio.file.Path;
47+
import java.nio.file.Paths;
48+
import java.time.Duration;
49+
import java.util.ArrayList;
50+
import java.util.Collections;
51+
import java.util.List;
52+
import java.util.Set;
53+
import java.util.regex.Pattern;
54+
import java.util.stream.Collectors;
55+
import java.lang.annotation.Retention;
56+
import java.lang.annotation.RetentionPolicy;
57+
import java.lang.annotation.Target;
58+
import java.lang.annotation.ElementType;
59+
60+
public class Snippets {
61+
62+
void AnnotationElementOverview() {
63+
// @start region="AnnotationElementOverview"
64+
List<AnnotationElement> typeAnnotations = new ArrayList<>();
65+
typeAnnotations.add(new AnnotationElement(Name.class, "com.example.HelloWorld"));
66+
typeAnnotations.add(new AnnotationElement(Label.class, "Hello World"));
67+
typeAnnotations.add(new AnnotationElement(Description.class, "Helps programmer getting started"));
68+
69+
List<AnnotationElement> fieldAnnotations = new ArrayList<>();
70+
fieldAnnotations.add(new AnnotationElement(Label.class, "Message"));
71+
72+
List<ValueDescriptor> fields = new ArrayList<>();
73+
fields.add(new ValueDescriptor(String.class, "message", fieldAnnotations));
74+
75+
EventFactory f = EventFactory.create(typeAnnotations, fields);
76+
Event event = f.newEvent();
77+
event.commit();
78+
// @end
79+
}
80+
81+
// @start region="EventOverview"
82+
public class Example {
83+
84+
@Label("Hello World")
85+
@Description("Helps programmer getting started")
86+
static class HelloWorld extends Event {
87+
@Label("Message")
88+
String message;
89+
}
90+
91+
public static void main(String... args) {
92+
HelloWorld event = new HelloWorld();
93+
event.message = "hello, world!";
94+
event.commit();
95+
}
96+
}
97+
// @end
98+
99+
void EventFactoryOverview() {
100+
// @start region="EventFactoryOverview"
101+
List<ValueDescriptor> fields = new ArrayList<>();
102+
List<AnnotationElement> messageAnnotations = Collections.singletonList(new AnnotationElement(Label.class, "Message"));
103+
fields.add(new ValueDescriptor(String.class, "message", messageAnnotations));
104+
List<AnnotationElement> numberAnnotations = Collections.singletonList(new AnnotationElement(Label.class, "Number"));
105+
fields.add(new ValueDescriptor(int.class, "number", numberAnnotations));
106+
107+
String[] category = { "Example", "Getting Started" };
108+
List<AnnotationElement> eventAnnotations = new ArrayList<>();
109+
eventAnnotations.add(new AnnotationElement(Name.class, "com.example.HelloWorld"));
110+
eventAnnotations.add(new AnnotationElement(Label.class, "Hello World"));
111+
eventAnnotations.add(new AnnotationElement(Description.class, "Helps programmer getting started"));
112+
eventAnnotations.add(new AnnotationElement(Category.class, category));
113+
114+
EventFactory f = EventFactory.create(eventAnnotations, fields);
115+
116+
Event event = f.newEvent();
117+
event.set(0, "hello, world!");
118+
event.set(1, 4711);
119+
event.commit();
120+
// @end
121+
}
122+
123+
void EventSettingOverview() throws Exception {
124+
// @start region="EventSettingOverview"
125+
Recording r = new Recording();
126+
r.enable("jdk.CPULoad")
127+
.withPeriod(Duration.ofSeconds(1));
128+
r.enable("jdk.FileWrite")
129+
.withoutStackTrace()
130+
.withThreshold(Duration.ofNanos(10));
131+
r.start();
132+
Thread.sleep(10_000);
133+
r.stop();
134+
r.dump(Files.createTempFile("recording", ".jfr"));
135+
// @end
136+
}
137+
138+
void FlightRecorderTakeSnapshot() throws Exception {
139+
// @start region="FlightRecorderTakeSnapshot"
140+
try (Recording snapshot = FlightRecorder.getFlightRecorder().takeSnapshot()) {
141+
if (snapshot.getSize() > 0) {
142+
snapshot.setMaxSize(100_000_000);
143+
snapshot.setMaxAge(Duration.ofMinutes(5));
144+
snapshot.dump(Paths.get("snapshot.jfr"));
145+
}
146+
}
147+
// @end
148+
}
149+
150+
// @start region="MetadataDefinitionOverview"
151+
@MetadataDefinition
152+
@Label("Severity")
153+
@Description("Value between 0 and 100 that indicates severity. 100 is most severe.")
154+
@Retention(RetentionPolicy.RUNTIME)
155+
@Target({ ElementType.TYPE })
156+
public @interface Severity {
157+
int value() default 50;
158+
}
159+
160+
@MetadataDefinition
161+
@Label("Transaction Id")
162+
@Relational
163+
@Retention(RetentionPolicy.RUNTIME)
164+
@Target({ ElementType.FIELD })
165+
public @interface TransactionId {
166+
}
167+
168+
@Severity(80)
169+
@Label("Transaction Blocked")
170+
class TransactionBlocked extends Event {
171+
@TransactionId
172+
@Label("Transaction")
173+
long transactionId1;
174+
175+
@TransactionId
176+
@Label("Transaction Blocker")
177+
long transactionId2;
178+
}
179+
// @end
180+
181+
void RecordingnOverview() throws Exception {
182+
// @start region="RecordingOverview"
183+
Configuration c = Configuration.getConfiguration("default");
184+
Recording r = new Recording(c);
185+
r.start();
186+
System.gc();
187+
Thread.sleep(5000);
188+
r.stop();
189+
r.dump(Files.createTempFile("my-recording", ".jfr"));
190+
// @end
191+
}
192+
193+
// @start region="SettingControlOverview1"
194+
final class RegExpControl extends SettingControl {
195+
private Pattern pattern = Pattern.compile(".*");
196+
197+
@Override
198+
public void setValue(String value) {
199+
this.pattern = Pattern.compile(value);
200+
}
201+
202+
@Override
203+
public String combine(Set<String> values) {
204+
return String.join("|", values);
205+
}
206+
207+
@Override
208+
public String getValue() {
209+
return pattern.toString();
210+
}
211+
212+
public boolean matches(String s) {
213+
return pattern.matcher(s).find();
214+
}
215+
}
216+
// @end
217+
218+
class HttpServlet {
219+
}
220+
221+
class HttpServletRequest {
222+
public String getRequestURI() {
223+
return null;
224+
}
225+
}
226+
227+
class HttpServletResponse {
228+
}
229+
230+
// @start region="SettingControlOverview2"
231+
abstract class HTTPRequest extends Event {
232+
@Label("Request URI")
233+
protected String uri;
234+
235+
@Label("Servlet URI Filter")
236+
@SettingDefinition
237+
protected boolean uriFilter(RegExpControl regExp) {
238+
return regExp.matches(uri);
239+
}
240+
}
241+
242+
@Label("HTTP Get Request")
243+
class HTTPGetRequest extends HTTPRequest {
244+
}
245+
246+
@Label("HTTP Post Request")
247+
class HTTPPostRequest extends HTTPRequest {
248+
}
249+
250+
class ExampleServlet extends HttpServlet {
251+
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
252+
HTTPGetRequest request = new HTTPGetRequest();
253+
request.begin();
254+
request.uri = req.getRequestURI();
255+
code: // @replace regex='code:' replacement="..."
256+
request.commit();
257+
}
258+
259+
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
260+
HTTPPostRequest request = new HTTPPostRequest();
261+
request.begin();
262+
request.uri = req.getRequestURI();
263+
code: // @replace regex='code:' replacement="..."
264+
request.commit();
265+
}
266+
}
267+
// @end
268+
269+
void SettingControlOverview3() {
270+
// @start region="SettingControlOverview3"
271+
Recording r = new Recording();
272+
r.enable("HTTPGetRequest").with("uriFilter", "https://www.example.com/list/.*");
273+
r.enable("HTTPPostRequest").with("uriFilter", "https://www.example.com/login/.*");
274+
r.start();
275+
// @end
276+
}
277+
278+
// @start region="SettingDefinitionOverview"
279+
class HelloWorld extends Event {
280+
281+
@Label("Message")
282+
String message;
283+
284+
@SettingDefinition
285+
@Label("Message Filter")
286+
public boolean filter(RegExpControl regExp) {
287+
return regExp.matches(message);
288+
}
289+
}
290+
// @end
291+
}

0 commit comments

Comments
 (0)
Please sign in to comment.