Skip to content

Commit 1d02c77

Browse files
committed
test: park thousands of virtual threads in synchronized methods, a wait and plain frames
1 parent 66ec26d commit 1d02c77

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

‎test/java/VirtualPackedMix.java‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import java.util.concurrent.CountDownLatch;
2+
import java.util.concurrent.locks.LockSupport;
3+
4+
// thousands of parked virtual threads whose frames include synchronized methods
5+
// and a wait, so packed frames sit next to frames that hold a monitor
6+
public class VirtualPackedMix {
7+
static final int COUNT = 2400;
8+
static final CountDownLatch parked = new CountDownLatch(COUNT);
9+
static final Object shared = new Object();
10+
static volatile boolean go;
11+
12+
public static void main(String[] args) throws Exception {
13+
long[] sums = new long[COUNT];
14+
Thread[] threads = new Thread[COUNT];
15+
for (int i = 0; i < COUNT; i++) {
16+
int id = i;
17+
threads[i] = Thread.ofVirtual().start(() -> sums[id] = switch (id % 3) {
18+
case 0 -> new VirtualPackedMix().locked(id, 2.5 * id, "a" + id);
19+
case 1 -> waiting(id);
20+
default -> plain(id, 1L << 40, (float) id);
21+
});
22+
}
23+
parked.await();
24+
while (!allParked(threads)) Thread.sleep(10);
25+
for (int id : new int[] {3, 4, 5}) {
26+
StackTraceElement[] trace = threads[id].getStackTrace();
27+
boolean found = false;
28+
for (StackTraceElement e : trace) found |= e.getMethodName().equals(id % 3 == 0 ? "locked" : id % 3 == 1 ? "waiting" : "plain");
29+
System.out.println("trace " + id + " " + found);
30+
}
31+
go = true;
32+
synchronized (shared) { shared.notifyAll(); }
33+
for (Thread t : threads) LockSupport.unpark(t);
34+
long total = 0;
35+
for (int i = 0; i < COUNT; i++) {
36+
threads[i].join();
37+
total += sums[i];
38+
}
39+
System.out.println("total " + total);
40+
}
41+
42+
static boolean allParked(Thread[] threads) {
43+
for (Thread t : threads) if (t.getState() != Thread.State.WAITING) return false;
44+
return true;
45+
}
46+
47+
synchronized long locked(int id, double d, String s) {
48+
parked.countDown();
49+
while (!go) LockSupport.park();
50+
return id + (long) d + s.length();
51+
}
52+
53+
static long waiting(int id) {
54+
synchronized (shared) {
55+
parked.countDown();
56+
while (!go) {
57+
try { shared.wait(); } catch (InterruptedException e) { return -1; }
58+
}
59+
}
60+
return id * 2L;
61+
}
62+
63+
static long plain(int id, long l, float f) {
64+
return id + deeper(id, l, f);
65+
}
66+
67+
static long deeper(int id, long l, float f) {
68+
long before = l + id;
69+
parked.countDown();
70+
while (!go) LockSupport.park();
71+
return before + (long) f;
72+
}
73+
}

0 commit comments

Comments
 (0)