Resource Constrained Thread Per Task Executor
Daniel Avery
danielaveryj at gmail.com
Tue May 14 01:56:26 UTC 2024
If you did need to integrate a semaphore into an ExecutorService, you might
find it easier to implement a ThreadFactory, and then leverage the utility
methods in Executors to get an ExecutorService.
```
Semaphore sem = new Semaphore(permits);
ThreadFactory factory1 = Thread.ofVirtual().factory();
ThreadFactory factory2 = runnable -> {
try {
sem.acquire();
return factory1.newThread(() -> {
try {
runnable.run();
} finally {
sem.release();
}
});
} catch (InterruptedException ie) { // interrupted in acquire()
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
} catch (Throwable t) { // threw in newThread()
sem.release();
throw t;
}
};
ExecutorService es = Executors.newThreadPerTaskExecutor(factory2);
```
- Daniel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20240513/f2cbecdc/attachment.htm>
More information about the loom-dev
mailing list