Reputation: 134
I have a problem with controlling queue of threads. My application uses MySQL database to read parts of data, processing it and showing results on screen. There is about 20 tasks in queue, but only one is processing at once. Also user might cancel current queue, and "ask" for another part of data from database. Now I'm using ThreadPoolExecutor with "discard oldest policy", because I am removing "oldest" part of data from queue, and replace it with "new" part, when user wants it. My problem is that even if corePoolSize is set to 1, sometimes there are 4 threads running at once. I don't know how to cleanly empty queue of not-started tasks. Now I'm using getQueue() and removing all items from list, but I read it is bad way. Also before adding new task to queue I want to check if there is no such task(with the same part of data) in queue and I have no idea how to achieve that.
Concluding:
1. Is there any way to force ThreadPoolExecutor to run just 1 task at once?
2. How to check queue to prevent duplicates of tasks (they are distinguished by String value)?
3. How to remove cleanly 'old' tasks from queue?
Or maybe I should use some other mechanism?
Any help is appreciated.
Upvotes: 3
Views: 318
Reputation: 10518
1. Is there any way to force ThreadPoolExecutor to run just 1 task at once?
Executors.newSingleThreadExecutor()
2. How to check queue to prevent duplicates of tasks (they are distinguished by String
Create your own list of tasks names. Add task name to this list before send task to executor and remove task name after task is executed.
3. How to remove cleanly 'old' tasks from queue?
When you add task to an executor you will get Future object. You can use future to cancel tasks. Or you can shutdown executor and create new one )
Upvotes: 2
Reputation: 62459
Perhaps using Executors.newSingleThreadExecutor()
will give you a better guarantee that there is exactly one thread in the pool.
Upvotes: 1