Size-limited queue that holds last N elements in Java

Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc: CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full. import java.util.Queue; import org.apache.commons.collections4.queue.CircularFifoQueue; Queue<Integer> fifo = new CircularFifoQueue<Integer>(2); fifo.add(1); fifo.add(2); fifo.add(3); System.out.println(fifo); // Observe the result: // [2, 3] If … Read more

Creating a blocking Queue in .NET?

That looks very unsafe (very little synchronization); how about something like: class SizeQueue<T> { private readonly Queue<T> queue = new Queue<T>(); private readonly int maxSize; public SizeQueue(int maxSize) { this.maxSize = maxSize; } public void Enqueue(T item) { lock (queue) { while (queue.Count >= maxSize) { Monitor.Wait(queue); } queue.Enqueue(item); if (queue.Count == 1) { // … Read more