更新时间:2022-10-14 23:13:10
在特定时间内使用什么机制来安排工作项?
我将使用一个java.util.concurrent.ScheduledExecutorService。
如果工作项是发送给actor的事件,
这使我成为一个可以阻止的项目设计,击败并行化的努力。尝试最小化或消除阻塞和全局状态。这些是可组合性和可扩展性的障碍。例如,考虑有一个专用线程等待文件到达,然后将事件触发给actor。或者查看java.nio的异步非阻塞I / O。
我不完全了解你的要求,但似乎你可以有一个线程/ actor寻找I / O事件。然后,作为您计划的工作项,计划创建非阻塞的actor的效果。让这些演员注册自己与I / O线程/ actor以接收他们关心的I / O事件的消息。
如何
。你有什么不是一个坏的设计在这方面。在地图中收集它们并调用future.cancel()。I have a fairly standard mechanism in Java for solving the problem:
- Work items must be scheduled to execute at a particular time
- Each work item must then wait on a condition becoming true
- Work items should be cancellable
The solution I use is as follows:
- Have a single-threaded scheduler to schedule my work items
- Have an
ExecutorService
(which may be multi-threaded)- Each scheduled work item then submits the actual work to the
ExecutorService
. The returnedFuture
is cached in a map. A completion service is used to remove the future from the cache when the work is completed- Items can be cancelled via the cached futures
Of course, my executor needs to be at least as big as the number of blocking work items I expect to have but this is not a problem in practice.
So now I'm coding in Scala and using the actor framework. Assuming that my work item can be encapsulated in an event sent to an actor:
- What mechanism would I use to schedule a work item for a specific time?
- If a work item is an event sent to an actor, how can I ensure that the backing thread pool is bigger than the number of items that can be blocking at the same time
- How can I cause a previously scheduled work item to be cancelled?
What mechanism would I use to schedule a work item for a specific time?
I would use a java.util.concurrent.ScheduledExecutorService.
If a work item is an event sent to an actor, how can I ensure that the backing thread pool is bigger than the number of items that can be blocking at the same time
This strikes me as a design that defeats the effort of parallelisation. Try to minimise or eliminate blocking and global state. These are barriers to composability and scalability. For example, consider having a single dedicated thread that waits for files to arrive and then fires events off to actors. Or look at java.nio for asynchronous non-blocking I/O.
I don't fully understand your requirements here, but it seems like you could have a single thread/actor looking for I/O events. Then as your scheduled "work items", schedule effects that create non-blocking actors. Have those actors register themselves with the I/O thread/actor to receive messages about I/O events that they care about.
How can I cause a previously scheduled work item to be cancelled?
ScheduledExecutorService
returns Futures. What you have is not a bad design in that regard. Collect them in a Map and call future.cancel().