Is it safe to use memorycache in multi threading?
While MemoryCache is indeed thread safe as other answers have specified, it does have a common multi threading issue – if 2 threads try to Get from (or check Contains) the cache at the same time, then both will miss the cache and both will end up generating the result and both will then add the result to the cache.
Is it possible that the cache is threadsafe?
The cache is threadsafe, but like others have stated, its possible that GetOrAdd will call the func multiple types if call from multiple types. As mentioned by @AmitE at the answer of @pimbrouwers, his example is not working as demonstrated here: It seems like GetOrCreate returns always the created entry.
How to write simple in memory cache in Java?
In the constructor, I created a daemon thread that scans every 5 seconds and cleans up expired objects, 5 seconds is a random number and you should think about cleaning interval. What’s wrong with this solution? If map contains a big amount of cached objects scan and clean up can take a time because it’s iterating through all values
How does Crunchify inmememorycache work in Java?
Here are the characteristic of the program CrunchifyInMemoryCache.java. Items will expire based on a time to live period. Cache will keep most recently used items if you will try to add more items then max specified. (apache common collections has a LRUMap, which, removes the least used entries from a fixed sized map)
Is the memorycache wrapper on NuGet thread safe?
This was one of the reasons I wrote LazyCache – a friendly wrapper on MemoryCache that solves these sorts of issues. It is also available on Nuget. As others have stated, MemoryCache is indeed thread safe. The thread safety of the data stored within it however, is entirely up to your using’s of it.
How does getoradd ( ) work in memorycache?
GetOrAdd () ( GetOrCreate () in the case of MemoryCache) will return the same, singular Lazy to all threads, the “extra” instances of Lazy are simply thrown away. Since the Lazy doesn’t do anything until .Value is called, only one instance of the object is ever constructed.