Resource Constrained Thread Per Task Executor
Colin Redmond
colin.redmond at outlook.com
Tue May 14 04:48:08 UTC 2024
Thanks for sharing that. It is a nice solution to my problem. I wouldn't have thought about having a ThreadFactory with a Semaphore for a ThreadFactory. But it looks simple and solves the problem.
________________________________
From: loom-dev <loom-dev-retn at openjdk.org> on behalf of Daniel Avery <danielaveryj at gmail.com>
Sent: May 13, 2024 6:56 PM
To: loom-dev <loom-dev at openjdk.java.net>
Subject: Re: Resource Constrained Thread Per Task Executor
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/20240514/5f4b53f9/attachment-0001.htm>
More information about the loom-dev
mailing list