HashMap used to store DateTime

Posted on

Problem

I have a scenario where I need to save a string as a key and DateTime as value into a hash map. Also, I need to remove strings older than 24 hours.

At the moment the HashMap is implemented as below:

HashMap<String, DateTime> sessions = new HashMap<>();
//Adding to the HashMap
sessions.put(session.toString(), DateTime.now());
//Removing from the HashMap
sessions.forEach((str, time)-> {
    if(time.clicks() < DateTime.now().minus(86400000).clicks())
        sessions.remove(str);
});

Would it be less overhead to save the DateTime clicks as Long datatype rather than saving the whole DateTime object? Like below:

HashMap<String, Long> sessions = new HashMap<>();
//Adding to the HashMap
sessions.put(session.toString(), DateTime.now().clicks);
//Removing from the HashMap
sessions.forEach((str, time)-> {
    if(time < DateTime.now().minus(86400000).clicks())
        sessions.remove(str);
});

Solution

I’ll go out on a limb and say most senior developers would discourage any form of datetime arithmetic involving raw numbers rather than DateTime objects. There are a whole heap of problems you can avoid (leap years, leap seconds, timezone changes etc.) by always using datetime objects rather than timestamps. See for example Falsehoods programmers believe about time. In short, the potential for bugs completely outweighs the tiny memory savings.

I would suggest the following:
a. Use a LinkedHashMap. Since, it keeps elements in insertion order, you should be able to optimize your code to ensure the moment you receive an entry less than 24 hours old, you can break out of the loop.
Please refer the doc below :
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html

  1. You will also definitely need top handle the multithreading issues with the map to avoid ConcurrentModificationException.
  2. Lastly, I agree with response above not to interfere with DateTime object just to have slightly lower memory footprint.
  3. Consider, how frequently you will be clearing out the entries in the map.

Leave a Reply

Your email address will not be published. Required fields are marked *