Home > Blockchain >  Java/Kotlin - Concurrent Linked Queue of a specific size
Java/Kotlin - Concurrent Linked Queue of a specific size

Time:09-23

I have a use-case where I am processing locations to use for event validation. This is a multi-threaded environment, so I'd like to use a thread safe queue data structure of some sort.

ConcurrentLinkedQueue does almost exactly what I want, but there is no way to specific the max size of the queue. I'd like to only be able to fit N elements in the queue, and then throw the "oldest" one away (FIFO for example) if adding an element would exceed the size of the queue.

LinkedBlockingQueue seems similar to what I want, but I DO NOT want the blocking behavior when the queue is full - I just want the oldest value to be evicted and the new value inserted.

Is there a default implementation of this that I could leverage? Or would it involve a custom implementation of a doubly linked list for example?

CodePudding user response:

Is there a default implementation of this that I could leverage?

To the best of my knowledge, there is no queue implementation in the standard library that discards enqueued objects without them having been explicitly removed. I would be inclined to interpret that as contrary to the general contract of the java.util.Queue interface, in fact. An object enqueued on a Queue should remain there until dequeued.

That does not mean you can't roll your own, even as an implementation of Queue. But I doubt that you could do it in a manner that is both thread safe and lock-free.

Or would it involve a custom implementation of a doubly linked list for example?

Your implementation options are pretty wide open. Among them are variations on wrapping or extending existing Queue or List implementations. I do not see what would be gained by implementing a linked list from scratch.

CodePudding user response:

If you're willing to venture into the world of Reactive Programming, Project Reactor's Flux has an onBackpressureBuffer method that takes a size limit and an overflow strategy. BufferOverflowStrategy.DROP_OLDEST has the behavior you're asking for.

  • Related