|
| 1 | +import java.util.Scanner; |
| 2 | +import java.util.concurrent.Executors; |
| 3 | + |
| 4 | +/** |
| 5 | + * Try to run in JDK 21 and 24. |
| 6 | + * To run: `java -Djdk.virtualThreadScheduler.parallelism=2 -Djdk.tracePinnedThreads=short SynchronizeVirtualThreadTest.java` |
| 7 | + */ |
| 8 | +public class SynchronizeVirtualThreadTest { |
| 9 | + public static void main(String[] args) { |
| 10 | + // platform threads runs normally |
| 11 | + // var executor = Executors.newFixedThreadPool(2); |
| 12 | + |
| 13 | + // until Java 24, with parallelism 2, only two virtual thread will run by time |
| 14 | + // the virtual threads gets pinned and blocked waiting forever |
| 15 | + var factory = Thread.ofVirtual().name("VT-", 0).factory(); |
| 16 | + var executor = Executors.newThreadPerTaskExecutor(factory); |
| 17 | + |
| 18 | + var riskOperation = new RiskOperation(); |
| 19 | + |
| 20 | + for (int i = 0; i < 5; i++) { |
| 21 | + executor.submit(riskOperation::doSomething); |
| 22 | + } |
| 23 | + |
| 24 | + while (!executor.isTerminated()) { |
| 25 | + ; |
| 26 | + } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +class RiskOperation { |
| 31 | + void doSomething() { |
| 32 | + log("About to start a synchronized work"); |
| 33 | + this.doSynchronizedWork(); |
| 34 | + log("Work done"); |
| 35 | + } |
| 36 | + |
| 37 | + synchronized void doSynchronizedWork() { |
| 38 | + log("Doing synchronized work..."); |
| 39 | + try { |
| 40 | + Thread.sleep(1_000); |
| 41 | + } catch (InterruptedException ex) {} |
| 42 | + } |
| 43 | + |
| 44 | + void log(String message) { |
| 45 | + System.out.printf("%s - %s%n", Thread.currentThread().toString(), message); |
| 46 | + } |
| 47 | +} |
0 commit comments