queue with time stamped elements within a time period

后端 未结 3 2260
孤街浪徒
孤街浪徒 2021-02-20 14:29

I want to store in a queue, datastructure does not matter, only the elements that I have inserted within say last 5 minutes from current time. Anything older should get removed

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 15:05

    I have implement a FadingLinkedList like

    public class FadingLinkedList {
    
    private transient Entry header = new Entry(null, null);
    
    /**
     * ms
     */
    private long livingTime;
    
    /**
     * Constructs FadingLinkedList with elements of living time livingTime in
     * milliseconds
     */
    public FadingLinkedList(long livingTime) {
        this.livingTime = livingTime;
    }
    
    /**
     * remove all faded elements,
     *
     * @return the count of not faded
     */
    public synchronized int removeFaded() {
        long now = System.nanoTime();
        int count = 0;
        Entry prev = header;// the last living Entry in the loop
        for (Entry e = header.next; e != null; e = e.next) {
            if (TimeUnit.NANOSECONDS.toMillis(now - e.birthTime) >= livingTime) {
                // cut off this list here.
                prev.next = null;
                break;
            }
            count++;
            prev = e;
        }
        return count;
    }
    
    /**
     * Returns the number of elements that not faded.
     */
    public int size() {
        return removeFaded();
    }
    
    public synchronized void push(E e) {
        Entry newEntry = new Entry(e, header.next);
        header.next = newEntry;
    }
    
    private static class Entry {
        E element;
        Entry next;
        long birthTime;
    
        Entry(E element, Entry next) {
            this.element = element;
            this.next = next;
            this.birthTime = System.nanoTime();
        }
    }
    
    public synchronized void clear() {
        header.next = null;
    }
    
    public synchronized int getAndClear() {
        int size = size();
        clear();
        return size;
    }
    

    }

提交回复
热议问题