Reza Shirin Nezhad
Reza Shirin Nezhad

Reputation: 127

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?

Upvotes: 1

Views: 1323

Answers (2)

Krešimir Nesek
Krešimir Nesek

Reputation: 5492

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....

Upvotes: 2

Max Farsikov
Max Farsikov

Reputation: 2763

Spring caching is more generic, flexible, and more complex mechanism than a simple getter. It allows to use different cache providers, configure cache invalidation... and many more.

If for your needs it is enough to have just a getter - you should use a getter, to keep your application as simple as possible.

Upvotes: 2

Related Questions