Reputation: 749
I am building a small cache with a Map which holds a cached result for some DB query. Assume that this cache is filled in a thread safe way. My question is about the entries in this cache, the objects of type Result.
Consider the following scenario:
Thread 1 reads from the cache and gets some Result object, call it R. Thread 2 wants the same object R to be killed so it makes a call to the cache kill the object R.
Seeing how both threads hold only a reference to the object R, there is a possibility that the object R suddenly becomes null for thread 1 since thread 2 has made a call to kill it.
How do I avoid this? Should I make a deep copy of the object R when a thread reads from the cache so that even if thread 2 kills the cache, then thread 1 will still be able to finish what it was doing without issues? Or is there another approach to this? My experience with threads and concurrency is not the biggest so be gentle...
Upvotes: 0
Views: 312
Reputation: 2812
If your "kill" operation modifies the internals of Result then you could have this problem. If it doesn't then no, the reference for the thread that already received it from the cache cannot become null. Deleting object from the map does not make references null.
Upvotes: 0
Reputation: 14164
Yes -- generally you treat Result as a value object. Thread 2 would remove it from the cache/ or overwrite the cache with a newer value, but would not generally damage/destroy the internal state of R.
Thread 2 "putting null into the cache" or "putting a new value into the cache" would not, of itself, affect any other references or threads using R. Nothing inside R will break, unless you specifically break it.. code requesting an object from the cache just won't be given that particular reference to R, anymore.
The pointer/or reference will change or be set to null, the state & fields of R itself won't.
This assumes that R doesn't hold resources that need to be freed..
If R did need to hold resources, which is not the usual case, then you might need to add an in-use counter and count both being in-use by being held in cache & being in-use by client code, such that R's resources only got released when the counter decremented to zero.
But this would be an unusual requirement.
Upvotes: 2