public class Test { private static final Object lock = new Object(); public static void main(String[] args) { try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 100; i++) { int taskId = i; executor.submit(() -> performTask(taskId)); } } System.out.println("All tasks completed."); } private static void performTask(int id) { System.out.printf("Task %d started. Thread: %s%n", id, Thread.currentThread()); synchronized (lock) { System.out.printf("Task %d acquired lock. Thread: %s%n", id, Thread.currentThread()); try { Thread.sleep(Duration.ofSeconds(2)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.printf("Task %d finished. Thread: %s%n", id, Thread.currentThread()); } } In theory this should behave like serial execution, but in practice it kind of freezes up like a deadlock.
I’ve been stuck on this for days and really need some help.
System.out.printf, i.e. the one that reports that the task has finished, then the deadlock goes away.printfprevents the "deadlock". This might be related to the synchronized insideprintf, but why does this happen if the code logic is correct?