Simple Java Solution with Cleanup routine


  • 0
    M

    We will cleanup old keys on every 100th second.
    If several million entries are added each second the solution does not scale very well. In that case we can maintain 10 different hashMaps representing 10 seconds and do lookup in each one of them in parallel.
    On 11th second we re-initialize the first hashmap with new one and so on.

    /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
        If this method returns false, the message will not be printed.
        The timestamp is in seconds granularity. */
    public boolean shouldPrintMessage(int timestamp, String message) {
        synchronized(timeMap){
            if(cleaner%100 == 0){
                cleanOldKeys(timestamp);
            }
            
         
            if(timeMap.containsKey(message)){
                Integer stamp = timeMap.get(message);
                if(stamp - 10 >= 10){
                    timeMap.put(message, timestamp);
                    return true;
                }else{
                    return false;
                }
            }else{
                 timeMap.put(message, timestamp);
                return true;
            }
        }
    }
    
    private void cleanOldKeys(int timestamp){
    
        for(Iterator<Map.Entry<String, Integer>> it = timeMap.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<String, Integer> entry = it.next();
            if(timestamp - entry.getValue() > 10) {
                it.remove();
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.