Let's say I have a complex object that is immutable that stores a bunch of data. Let's call this type MyDataCache
.
Now, let's say I have a MyDataCacheManager
which holds a reference to a MyDataCache
. Callers can ask the manager for a reference of the cache and it will give that. There are 1000s of calls per second to get a reference for reading from the cache.
Very infrequently (once every few hours), the cache needs to be updated. So my thinking is, a new MyDataCache
is created in the background with the refreshed data and then the reference inside the manager is swapped.
However, I need this to be thread safe. Given, MyDataCache
is immutable can I create a method in the manager that simply takes a new MyDataCache
as a parameter and sets it as its new internal reference? Given it's just a reference switch of an immutable object, would this be thread safe?
If not, can I use Interlocked.Exchange
to achieve this?
Ultimately, given 1000s of reads per second and only 1 update every few hours, what's the best thread safety strategy for this?