<div dir="ltr"><div dir="ltr"><br></div><br><div class="gmail_quote gmail_quote_container"><div dir="ltr" class="gmail_attr">Alan Bateman <<a href="mailto:alan.bateman@oracle.com">alan.bateman@oracle.com</a>> ezt írta (időpont: 2025. dec. 24., Sze, 9:12):<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">On 23/12/2025 21:58, Attila Kelemen wrote:<br>
> Holo's response is probably your best bet for STS. Otherwise, Alan <br>
> alluded to an implementation like this (disclaimer: I just typed it <br>
> into an email, did no testing in anyway):<br>
><br>
> ```<br>
> ThreadFactory limitedFactory(int limit, ThreadFactory wrapped) {<br>
> var semaphore = new Semaphore(limit);<br>
> return r -> {<br>
> var thread = wrapped.newThread(() -> {<br>
> try {<br>
> r.run();<br>
> } finally {<br>
> semaphore.release();<br>
> }<br>
> });<br>
> semaphore.acquireUninterruptibly();<br>
> return thread;<br>
> };<br>
> }<br>
> ```<br>
><br>
> but as I noted previously, this has the problem that no API makes a <br>
> general promise that a thread will actually be started.<br>
<br>
If you move the acquire into the wrapped task then it will be closer to <br>
some of the sketches in previous discussions here. That would avoid the <br>
main task blocking in newThread, and goes to your comment about creating <br>
but not starting threads too. There may be > limit Threads but at most <br>
min(limit, #ncores) would execute concurrently. Using acquire rather <br>
than acquireUninterruptibly, and handling the InterruptedException, <br>
would make also make it more responsive when the scope is cancelled <br>
before some of these subtasks run.<br><br></blockquote><div><br></div><div>That would be rather bad, because the point is the push back on the main thread to stop producing tasks. Otherwise, if there is no push back, then - in a situation where the producer is much faster than the consumer - gazillions (maybe even an unbounded number of them) of threads could be created which is a massive resource leak. As for `acquire` vs. `acquireUniterruptibly`, I just used it for simplicity here to avoid the catch. Shows to tell how bad this interruption based cancellation is.</div></div></div>