File: ThreadSleepEvent.java

package info (click to toggle)
openjdk-24 24.0.2%2B12-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 831,900 kB
  • sloc: java: 5,677,020; cpp: 1,323,154; xml: 1,320,524; ansic: 486,889; asm: 405,131; objc: 21,025; sh: 15,221; javascript: 11,049; python: 8,222; makefile: 2,504; perl: 357; awk: 351; sed: 172; pascal: 103; exp: 54; jsp: 24; csh: 3
file content (196 lines) | stat: -rw-r--r-- 7,093 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/*
 * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * @test
 * @summary Test that Thread.sleep emits a JFR jdk.ThreadSleep event
 * @requires vm.hasJFR
 * @modules jdk.jfr
 * @run junit ThreadSleepEvent
 */

import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.concurrent.TimeUnit.*;

import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingFile;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;

class ThreadSleepEvent {
    private static final String THREAD_SLEEP_EVENT_NAME = "jdk.ThreadSleep";

    static Stream<ThreadFactory> threadFactories() {
        return Stream.of(
                Thread.ofPlatform().factory(),
                Thread.ofVirtual().factory()
        );
    }

    // Arguments.of(ThreadFactory, millis)
    static Stream<Arguments> threadFactoryAndMillis() {
        long[] millis = {0, 1000, Long.MAX_VALUE};
        return threadFactories()
                .flatMap(f -> LongStream.of(millis)
                        .mapToObj(ms -> Arguments.of(f, ms)));
    }

    // Arguments.of(ThreadFactory, millis, nanos)
    static Stream<Arguments> threadFactoryAndMillisAndNanos() {
        int[] nanos = {0, 1000, 999_999};
        return threadFactoryAndMillis().flatMap(a -> IntStream.of(nanos)
                .mapToObj(ns -> Arguments.of(a.get()[0], a.get()[1], ns)));
    }

    // Arguments.of(ThreadFactory, Duration)
    static Stream<Arguments> threadFactoryAndDuration() {
        Duration[] durations = {
                Duration.ofNanos(0),
                Duration.ofSeconds(1),
                Duration.ofSeconds(Long.MAX_VALUE, 999_999_999)
        };
        return threadFactories()
                .flatMap(f -> Stream.of(durations)
                        .map(d -> Arguments.of(f, d)));
    }

    /**
     * Test Thread.sleep(long) emits event.
     */
    @ParameterizedTest
    @MethodSource("threadFactoryAndMillis")
    void testSleep(ThreadFactory factory, long millis) throws Exception {
        long expectedTime = MILLISECONDS.toNanos(millis);
        long recordedTime = testSleep(factory, () -> Thread.sleep(millis));
        assertEquals(expectedTime, recordedTime);
    }

    /**
     * Test Thread.sleep(long, int) emits event.
     */
    @ParameterizedTest
    @MethodSource("threadFactoryAndMillisAndNanos")
    void testSleep(ThreadFactory factory, long millis, int nanos) throws Exception {
        long expectedTime = MILLISECONDS.toNanos(millis);
        expectedTime += Math.min(Long.MAX_VALUE - expectedTime, nanos);
        long recordedTime = testSleep(factory, () -> Thread.sleep(millis, nanos));
        assertEquals(expectedTime, recordedTime);
    }

    /**
     * Test Thread.sleep(Duration) emits event.
     */
    @ParameterizedTest
    @MethodSource("threadFactoryAndDuration")
    void testSleep(ThreadFactory factory, Duration duration) throws Exception {
        long expectedTime = NANOSECONDS.convert(duration);
        long recordedTime = testSleep(factory, () -> Thread.sleep(duration));
        assertEquals(expectedTime, recordedTime);
    }

    /**
     * Test that sleeper emits event, returning the recorded sleep time.
     */
    long testSleep(ThreadFactory factory, Sleeper sleeper) throws Exception {
        try (Recording recording = new Recording()) {
            long tid;

            recording.enable(THREAD_SLEEP_EVENT_NAME);
            recording.start();
            try {

                // start thread to run sleeper task
                var latch = new CountDownLatch(1);
                Thread thread = factory.newThread(() -> {
                    latch.countDown();
                    try {
                        sleeper.run();
                    } catch (InterruptedException e) {
                        // ignore;
                    }
                });
                thread.start();

                // wait for thread to execute
                latch.await();

                // don't wait for the sleep time
                thread.interrupt();

                thread.join();
                tid = thread.threadId();
            } finally {
                recording.stop();
            }

            // find the ThreadSleep event recorded by the thread
            RecordedEvent event = find(recording, THREAD_SLEEP_EVENT_NAME, tid).orElseThrow();
            return event.getLong("time");
        }
    }

    private interface Sleeper {
        void run() throws InterruptedException;
    }

    /**
     * Find a recorded event with the given name and recorded by a thread with the
     * given thread ID.
     */
    private static Optional<RecordedEvent> find(Recording recording,
                                                String name,
                                                long tid) throws Exception {
        Path recordingFile = recordingFile(recording);
        List<RecordedEvent> events = RecordingFile.readAllEvents(recordingFile);
        return events.stream()
                .filter(e -> e.getEventType().getName().equals(name)
                        && e.getThread().getJavaThreadId() == tid)
                .findAny();
    }

    /**
     * Return the file path to the recording file.
     */
    private static Path recordingFile(Recording recording) throws Exception {
        Path recordingFile = recording.getDestination();
        if (recordingFile == null) {
            ProcessHandle h = ProcessHandle.current();
            recordingFile = Path.of("recording-" + recording.getId() + "-pid" + h.pid() + ".jfr");
            recording.dump(recordingFile);
        }
        return recordingFile;
    }
}