简体   繁体   中英

Java Thread Pool that gets the last task added to the BlockingQueue and discard the others

I want a thread pool with a single thread but with a peculiar behavior for the BlockingQueue :

If I add a job to the queue and then add another job (making the queue hold two jobs), I want the thread to ignore the first job added and get the last one. So, everytime the thread gets a task from the queue, I want it to get the last job added to the queue and discard the others.

Is there any default BlockingQueue with this behavior? What would be the best strategy to achieve this? Should I implement my own BlockingQueue ? If yes, from which BlockingQueue should I start from?

My initial idea was to create a bounded blocking queue with capacity for only one task, but that when it's full and receives another task, it swaps the tasks discarding the task that was added earlier. Do I make sense?

You are on the right track with creating a bounded blocking queue with capacity for only one task. Additionally, configure your ThreadPoolExecutor with a DiscardOldestPolicy . Thus, whenever a second task is submitted, it doesn't fit into the queue and according to the policy the older one gets discarded.

Compare with the constructor ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue, RejectedExecutionHandler)

I would use a an atomic variable. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicReference.html

Example:

AtomicReference<X> task_;
//Pop
public X pop() { return task_.getAndSet(NULL); }
//Push
public X push (X val) { return task_.getAndSet(val); }

It is also wait-free in design.

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