Storing recent search phrases I have a search on a very simple spring-powered website and I want to display 10 recent inputs:

import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

@Component
public class RecentPhrases implements DisposableBean {
    static final int SIZE = 10;
    private final ExecutorService offeringService = Executors.newFixedThreadPool(1);
    private final ConcurrentMap&lt;String, Long&gt; phrases = new ConcurrentHashMap&lt;&gt;();

    @Override
    public void destroy() {
        offeringService.shutdownNow();
    }

    public void offer(final String phrase) {
        offeringService.execute(() -&gt; {
            phrases.put(phrase, System.currentTimeMillis());
            while (phrases.size() &gt; SIZE) {
                long oldestAge = Long.MAX_VALUE;
                String oldestPhrase = null;
                for (Entry&lt;String, Long&gt; entry : phrases.entrySet()) {
                    if (entry.getValue() &lt; oldestAge) {
                        oldestAge = entry.getValue();
                        oldestPhrase = entry.getKey();
                    }
                }
                phrases.remove(oldestPhrase);
            }
        });
    }

    public Collection&lt;String&gt; getRecent() {
        return phrases.keySet();
    }

}


Is there some simpler solution that will be lightweight enough to not update the underlying collection in a separate thread?
A LinkedHashSet would be simpler:


When the size reaches the limit, simply remove the first entry, no need to iterate
When adding an entry, if it already exists, you'd have to reinsert it to update the order: remove and then add
No more need to worry about the time of insert


Another advantage of this method is that the entries will be naturally ordered. In your current solution they are unordered, which could appear odd to users. This is not a big advantage though, because you could easily sort before returning the collection.