Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache objects as Immutable classes

I am asking very generic question and the answer can vary from requirement to requirement, but for "general" or "rule of thumb", can we say the following is a good design rule:

The classes to be cached (static/reference data) should be designed as immutable, with exceptions reasoned.

What could be design/performance issues with the above statement, if this is not true?

like image 648
Sandeep Jindal Avatar asked Dec 14 '25 04:12

Sandeep Jindal


1 Answers

@JohnB has a good answer about the underlying data.

If, however, the question is referring to the immutability of the cached classes themselves (which are holding the data in the cache), then the answer is that mutable classes can cause thread-safety issues if the instances of the classes are referenced by multiple threads (as can often happen with data shared via a cache). Additionally, "accidental" modification of the data may occur, where a shared instance is unintentionally modified (because the modifying code did not know that the data was shared).

like image 191
jtahlborn Avatar answered Dec 15 '25 17:12

jtahlborn