1 /*
 2  * Copyright (c) 2020, 2021, 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.
 8  *
 9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 /**
25  * @test
26  * @summary Stress test Thread.sleep
27  * @requires vm.debug != true
28  * @compile --enable-preview -source ${jdk.version} SleepALot.java
29  * @run main/othervm --enable-preview SleepALot
30  */
31 
32 /**
33  * @test
34  * @requires vm.debug == true
35  * @compile --enable-preview -source ${jdk.version} SleepALot.java
36  * @run main/othervm/timeout=300 --enable-preview SleepALot 200000
37  */
38 
39 import java.time.Duration;
40 import java.time.Instant;
41 import java.util.concurrent.atomic.AtomicInteger;
42 
43 public class SleepALot {
44 
45     public static void main(String[] args) throws Exception {
46         int iterations = 1_000_000;
47         if (args.length > 0) {
48             iterations = Integer.parseInt(args[0]);
49         }
50         final int ITERATIONS = iterations;
51 
52         AtomicInteger count = new AtomicInteger();
53 
54         Thread thread = Thread.ofVirtual().start(() -> {
55             while (count.incrementAndGet() < ITERATIONS) {
56                 try {
57                     Thread.sleep(Duration.ofNanos(100));
58                 } catch (InterruptedException ignore) { }
59             }
60         });
61 
62         boolean terminated;
63         do {
64             terminated = thread.join(Duration.ofSeconds(1));
65             System.out.println(Instant.now() + " => " + count.get());
66         } while (!terminated);
67 
68         int countValue = count.get();
69         if (countValue != ITERATIONS) {
70             throw new RuntimeException("count = " + countValue);
71         }
72     }
73 }