简体   繁体   English

ExecutorService空闲任务

[英]ExecutorService idle tasks

I use the java.util.ExecutorService to handle tasks, sometimes with only one worker. 我使用java.util.ExecutorService来处理任务,有时只有一个工作人员。 Not I'd like to add something like idle tasks, to preload data from the database and similar stuff while nothing is happening and the user has selected some item. 我不希望添加诸如闲置任务之类的东西,以在什么都没有发生并且用户选择了某些项目的情况下从数据库和类似内容中预加载数据。

My first idea was to just add it as a task when the user selects something, because when the user starts an interaction with the selection, the data are needed and have to be loaded either way. 我的第一个想法是在用户选择某项内容时将其添加为任务,因为当用户开始与所选内容进行交互时,需要数据并且必须以任何一种方式加载数据。

The problem with this approach is that when the user selects another item without doing something with the first selection, then there is this huge task in the Executor which only makes everything slower. 这种方法的问题在于,当用户选择另一个项目而没有对第一个选择做任何事情时,执行器中就有一项艰巨的任务,这只会使一切变慢。

Any simple ideas how I could start something like that? 有什么简单的主意可以开始这样的事情吗? I really don't want to build a huge management class to handle it and classify tasks or stuff like that. 我真的不想建立一个庞大的管理类来处理它并分类任务或类似的东西。

So what about using PriorityBlockingQueue? 那么使用PriorityBlockingQueue呢? Keep your tasks in that queue, give idle tasks low priority, so that they are always on the end of the queue. 将您的任务放在该队列中,给空闲任务低优先级,以便它们始终在队列的末尾。 Implement your pool's runnables so that they simply take the highest priority task from the queue and execute it. 实现池的可运行对象,以便它们仅从队列中获取优先级最高的任务并执行它。

To be sure that executing idle tasks will be replaced by more important ones, you can implement them to be executed in short chunks and placed back in the queue after each chunk is finished. 为确保将执行的空闲任务替换为更重要的任务,您可以将它们实现为以短块形式执行,并在每个块完成后放回队列中。 If something more important was placed in the queue in the meantime, it will be taken next, if not, idle task will be fetched once again from the queue. 如果与此同时将更重要的内容放置在队列中,则将接下来处理,否则,将从队列中再次获取空闲任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM