[StructuredTaskScope] Poor man's "back pressure" ?

Attila Kelemen attila.kelemen85 at gmail.com
Wed Dec 24 11:18:38 UTC 2025


Alan Bateman <alan.bateman at oracle.com> ezt írta (időpont: 2025. dec. 24.,
Sze, 9:12):

> On 23/12/2025 21:58, Attila Kelemen wrote:
> > Holo's response is probably your best bet for STS. Otherwise, Alan
> > alluded to an implementation like this (disclaimer: I just typed it
> > into an email, did no testing in anyway):
> >
> > ```
> > ThreadFactory limitedFactory(int limit, ThreadFactory wrapped) {
> >     var semaphore = new Semaphore(limit);
> >     return r -> {
> >         var thread = wrapped.newThread(() -> {
> >             try {
> >                 r.run();
> >             } finally {
> >                 semaphore.release();
> >             }
> >         });
> >         semaphore.acquireUninterruptibly();
> >         return thread;
> >     };
> > }
> > ```
> >
> > but as I noted previously, this has the problem that no API makes a
> > general promise that a thread will actually be started.
>
> If you move the acquire into the wrapped task then it will be closer to
> some of the sketches in previous discussions here. That would avoid the
> main task blocking in newThread, and goes to your comment about creating
> but not starting threads too.  There may be > limit Threads but at most
> min(limit, #ncores) would execute concurrently. Using acquire rather
> than acquireUninterruptibly, and handling the InterruptedException,
> would make also make it more responsive when the scope is cancelled
> before some of these subtasks run.
>
>
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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20251224/34d49559/attachment-0001.htm>


More information about the loom-dev mailing list