Structured Concurrency Feedback

Filip Egeric egericf at gmail.com
Tue Oct 21 11:57:59 UTC 2025


>
> Have you tried using a ThreadFactory factory instead? A custom
> ThreadFactory can be used to wrap all tasks so you get the
> acquire/release to limit concurrency.


I haven't tried that. Would this be the optimal solution with that approach?

class LimitedThreadFactory implements ThreadFactory {
    private final Semaphore semaphore;

    private LimitedThreadFactory(int n) {
        this.semaphore = new Semaphore(n, true);
    }

    static LimitedThreadFactory of(int n) {
        return new LimitedThreadFactory(n);
    }

    @Override
    public Thread newThread(Runnable r) {
        return Thread.ofVirtual()
                .unstarted(() -> {
                    try {
                        semaphore.acquire();
                        r.run();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException(e);
                    } finally {
                        semaphore.release();
                    }
                });
    }
}



On Tue, Oct 21, 2025 at 12:06 PM Alan Bateman <alan.bateman at oracle.com>
wrote:

>
>
> On 21/10/2025 08:40, Filip Egeric wrote:
> > Hello,
> >
> > I would like to follow up on this one, because I also found myself
> > creating a wrapper similar to this one, but for a different reason.
> > Specifically, when I want to limit concurrency in order to not exceed
> > a rate limit somewhere.
>
> Have you tried using a ThreadFactory factory instead? A custom
> ThreadFactory can be used to wrap all tasks so you get the
> acquire/release to limit concurrency.
>
> -Alan
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20251021/c48afe2e/attachment.htm>


More information about the loom-dev mailing list