Is there a fixed sized queue which removes excessive elements?
A quick way to implement this is to use a LinkedBlockingDeque with a fixed capacity. Establish your capacity and it will auto-remove the oldest element when new ones exceed this limit. Here's a simple demonstration:
Here, the queue always operates within the specified capacity with automatic removal of the oldest element.
Implementing fixed-size queue with LinkedHashMap
A powerful component in Java is LinkedHashMap, which can be tuned to a self-maintaining fixed-size queue. Overriding removeEldestEntry allows you to auto-purge the stale entries.
Library to the rescue: Guava and Apache Commons
Why reinvent the wheel when libraries exist? Meet Google Guava's EvictingQueue and Apache Commons' CircularFifoQueue - they are your ready-to-use solution for a fixed-size queue with oldest element auto-eviction.
Remember, both these libraries yell "no entry" to null elements.
Low-key solution with ArrayDeque
For non-concurrent tasks, and love for simplicity, ArrayDeque might be your perfect match. Wrap your methods to enforce size maintenance:
Pointers for choosing your implementation
Factor in thread-safety, performance and null support for choosing your queue.
LinkedBlockingDeque: Safety first! Thread-safe but with extra overhead.- Custom
LinkedHashMap: Your rules, your game. Requires subclassing and overriding skills. - Third-party libraries: Ready-made solutions, just a dependency away.
ArrayDequewrapping: Swift and easy for non-concurrent tasks, might lack some advanced features.
Taking control with AbstractQueue
When it's all about customization, extend AbstractQueue to forge a fixed-size queue.
Was this article helpful?