<div dir="ltr">In my opinion, the core of the issue is not the behavior of close (if it did shutdownNow, then there are other nasty things which could happen, and would be equally surprising, but in other circumstances). The root of the problem is that thread interruption is a poor way to manage cancellation (they suffer from the same issue as global variables do). This poor cancellation mechanism was the main reason I created my own executor framework a long time ago. I wish Java never tried to use thread interrupts for cancellation.</div><br><div class="gmail_quote gmail_quote_container"><div dir="ltr" class="gmail_attr">Stig Rohde Døssing <<a href="mailto:stigdoessing@gmail.com">stigdoessing@gmail.com</a>> ezt írta (időpont: 2025. dec. 1., H, 21:17):<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr"><div>Hi,</div><div><br></div><div>I stumbled on a minor landmine with newVirtualThreadPerTaskExecutor, and figured I'd share in case something can be done to communicate this behavior a little better, because it caught me by surprise.</div><div><br></div><div>JEP 444 suggests code like the following<br><br>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br> var future1 = executor.submit(() -> fetchURL(url1));<br> var future2 = executor.submit(() -> fetchURL(url2));<br> response.send(future1.get() + future2.get());<br>} catch (ExecutionException | InterruptedException e) {<br> response.fail(e);<br>}<br><br></div><div>This led me to believe that I could write code like that, and get something that reacts to interrupts promptly. But unfortunately, the close method on this executor does not interrupt the two submitted fetches. Instead, if the main thread in this code is interrupted, the thread will block until the two fetches complete on their own time, and then it will fail the request, which seems a little silly. </div><div><br></div><div>Due to how try-with-resources works, the executor is closed before the catch block is hit, so in order to "stop early" when interrupted, you'd need to add a nested try-catch inside the try-with-resources to either interrupt the two futures or call shutdownNow on the executor when the main thread is interrupted.</div><div><br></div><div>I know that the structured concurrency API will be a better fit for this kind of thing, but given that virtual threads are likely to spend a lot of their time blocking waiting for something to occur, it seems a little unfortunate that the ThreadPerTaskExecutor for virtual threads doesn't do shutdownNow on close when used in the most straightforward way.</div></div>
</blockquote></div>