Search code examples
javaspringspring-cache

What's difference of using Spring Cache and keeping data in a variable?


A couple of days ago i implemented Caching feature in Spring framework in a project and that was interesting but now this question has been brought to my mind that what is difference of using Spring Cache and fetching or initializing data on application startup and keeping that in a variable whitin a spring bean which can be accessed via a getter?


Solution

  • If you have a single application instance, you don't care about any of more complex features (listed below) and you synchronize access to the variable correctly for multi-threaded use, there's no difference. Cache is cache - you have temporarily stored a value that is otherwise expensive to calculate or fetch.

    However, Spring Cache provides generic interface to specialized caching subsystems (for example EhCache, Redis....). In EhCache you can configure things like:

    • How many elements to keep in cache (to limit memory usage)
    • It manages LRU expiry if configured (e.g. least recently used elements will be removed from cache after certain configured tresholds are met)
    • You can choose whether or not to persist cache to disk or keep it only in memory or both
    • You could access cache from multiple application instances
    • Etc....