简体   繁体   中英

ExecutorService idle tasks

I use the java.util.ExecutorService to handle tasks, sometimes with only one worker. 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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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