Search code examples
javaspringrestdaoconcurrenthashmap

DAO using a ConcurrentHashMap


Is it ok to have a REST Webservice (Spring and Jersey) that uses a DAO with a ConcurrentHashMap to store the data, or should I avoid it and use some kind of in-memory DB?

It's an sample application, so I don't mind losing the data every time the application stops.


Solution

  • You can use ConcurrentHashMap, but you will have some difficulties when:

    • trying to do 2 and more actions in same "transaction", you should synchronize such actions with other threads, as ConcurrentHashMap is successfully works only with one operation;
    • trying to search not by Map key but some other field of the Map.Entry.value Object.

    ConcurrentHashMap is for other purposes. So, I'll advise to use any in-memory DB.