How to prevent loading a value that is not in the cache multiple times at the same time, in an efficient way?
A typical use of the cache is the following pseudo-code:
Object get(Object key) { Object value = cache.get(key); if (value == null) { value = loadFromService(key); cache.set(key,value); } return value; }
Problem: before loading the value from the service (Database, WebService, RemoteEJB or something else), the second call can be made at the same time, which will start the value again.
For example, when I cache all the elements for user X, and this user is often browsed and has many elements, there is a high probability of simultaneously invoking a load of all its elements, which leads to a large load on the server.
I could make the get function synchronized , but this will make other search queries wait, which doesn't make much sense. I can create a new lock for each key, but I donβt know whether it is worth managing so many locks in Java (this part depends on the language, the reason I marked it as java ).
Or is there another approach I could use? If so, what would be most effective?
Danubian sailor
source share