Do I need to synchronize the cache?

This seems like a naive question, but I entered into a discussion with a colleague, where he argued that there was no need for the cache to be thread safe / synchronized, since I would assume that it does not matter which introduces the value, since the value for a given key must be “permanent” (in the sense that it comes from the same source in the end). If the values ​​can easily change, then the cache itself does not seem useful (in this case, if you are interested in the value "currently correct", you should go to the source).

The main reason I see synchronization with at least GET is that if it’s very expensive to skip in the cache and you don’t want multiple threads to exit to get a value to return to the cache. Even then, you will need something that actually blocks all consumers during the read-select cycle.

In any case, my working assumption is that the hash is inherently thread safe, because for any combination {key, value} this value is zero or something that does not matter who goes there "first" to write.

Question: is this a reasonable assumption?

Update: the real area of ​​my question is related to very simple id-> value (or {parameters} → {calculated value} style caches, where regardless of who writes to the cache, the value will be the same and we are just trying to save on "recounting "/ return to the database. The actual schedule of the object does not matter, and the cache is usually durable.

+3
source share
5 answers

. , - /? , - -, , ? - -. , - ( ), , - , .

+4

. , (RCU, ..). . , ( , ).

+2

( ), . .:)

+1

, . , , . , DMV ( ). , , , , , . - - , , .

Yes, any piece of data can be permanent, but databases usually contain data that, if not updated together and atomically, can lead to database clients getting incorrect or incomplete or inconsistent results.

+1
source

If you use Java 5 or higher, you can use ConcurrentHashMap. It supports multiple readers and writers in streaming mode.

0
source

Source: https://habr.com/ru/post/1702497/


All Articles