1 /* 2 * Copyright (c) 2024, 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.getStackTrace on a virtual thread in timed-Object.wait 27 * @requires vm.debug != true 28 * @run main/othervm GetStackTraceALotWithTimedWait 100000 29 */ 30 31 /* 32 * @test 33 * @requires vm.debug == true 34 * @run main/othervm GetStackTraceALotWithTimedWait 50000 35 */ 36 37 import java.time.Instant; 38 import java.util.ArrayList; 39 import java.util.concurrent.Executors; 40 import java.util.concurrent.ThreadLocalRandom; 41 import java.util.concurrent.atomic.AtomicBoolean; 42 import java.util.concurrent.atomic.AtomicReference; 43 44 public class GetStackTraceALotWithTimedWait { 45 46 public static void main(String[] args) throws Exception { 47 int iterations = args.length > 0 ? Integer.parseInt(args[0]) : 100_000; 48 49 try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { 50 var done = new AtomicBoolean(); 51 var threads = new ArrayList<Thread>(); 52 53 // start threads that invoke Object.wait with a short timeout 54 int nthreads = Runtime.getRuntime().availableProcessors(); 55 for (int i = 0; i < nthreads; i++) { 56 var ref = new AtomicReference<Thread>(); 57 var lock = new Object(); 58 executor.submit(() -> { 59 ref.set(Thread.currentThread()); 60 while (!done.get()) { 61 synchronized (lock) { 62 int delay = 1 + ThreadLocalRandom.current().nextInt(20); 63 lock.wait(delay); 64 } 65 } 66 return null; 67 }); 68 Thread thread; 69 while ((thread = ref.get()) == null) { 70 Thread.sleep(20); 71 } 72 threads.add(thread); 73 } 74 75 // hammer on Thread.getStackTrace 76 try { 77 for (int i = 1; i <= iterations; i++) { 78 if ((i % 1000) == 0) { 79 System.out.println(Instant.now() + " => " + i + " of " + iterations); 80 } 81 for (Thread thread : threads) { 82 thread.getStackTrace(); 83 } 84 } 85 } finally { 86 done.set(true); 87 } 88 } 89 } 90 } 91