# Java time-to-live collection

Here's a class I made in java. It's pretty simple, the description of what it does is in the comment. I'd appreciate any feedback.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
* An unordered, duplicate-allowing collection of items that are added with a
* time-to-live, and will automatically be considered not a part of the
*/
public class TTLBag<E> implements Iterable<E> {

private class Element {

E item;
long expires;

Element(E item, long expires) {
this.item = item;
this.expires = expires;
}

}

private List<Element> contents = new ArrayList<>();

public void add(E item, long timeToLive) {
}

@Override
public Iterator<E> iterator() {
long time = System.currentTimeMillis();
contents.removeIf(element -> element.expires > time);
return contents.stream().map(element -> element.item).iterator();
}

}

• Adding few unit tests would be a good start – JBM Mar 24 '17 at 22:47
• Be aware that currentTimeMillis() is not monotonic - it jumps back and forth whenever the time is synced to a time server. A better alternative is System.nanoTime() stackoverflow.com/questions/351565/… – JBM Mar 24 '17 at 23:12
• Not sure if it makes a problem, but the expiration logic is applied at the moment the iterator is requested. However, the actual access to an item will happen later; this way, items which expire by that moment are still presented to the client. – JBM Mar 24 '17 at 23:20
• I support the comment of @JBM. But even if you implement the iteraror interface yourself: There will always be a time delay of unknown length between the call to hasNext() and next() where an element could reach its expiration, so that especially at the end of the iteration hasNext() may return true whereas next() has no element left to deliver and needs to throw a NoSuchElementException. You may lower the risk by sorting the elements by expiration time ascending, since already delivered elements may not affect the not yet delivered elements when expiring. – Timothy Truckle Mar 25 '17 at 12:04