Search code examples
javaspring-mvcpersistence

Why use a database instead of singleton bean fields?


My use case is a real-time Spring MVC application that deals with a small amount of non-critical data which "churns" rapidly. The data consists of around 20 key-value String pairs. It is pulled in on schedule from an external API, can be modified by an end user interacting with the webapp, and is used to produce parameters in a POST to another external API on a schedule.

This may be very obvious, perhaps too obvious to have a answer I can find anywhere, but basically why would I keep the data in a DB as opposed to using a dedicated singleton class with thread-safe fields such as a ConcurrentHashMap, which would then be injected into any @Services that need it? My initial feeling is that a class such as this would allow quicker read/writes than even an in-memory DB, yet every example I have seen relies on a "proper" DB:

@Repository
public class DataStore{

  private Map data = new ConcurrentHashMap<String, String>();

  //...getters and setters etc..
}

Thanks for any thoughts!


Solution

  • You can use a ConcurrentMap to store your key/value pairs in memory, nothing wrong with it. But "proper" DB provides you mostly with persistence, the data will be still there when you restart your application. DB also provides you with atomicity, which Map on its own does not (however it can be added by simple locking).