>
> 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 <[email protected]>
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
>