I'm trying to implement following scenario and unable to come up with a solution.
In my web service I've cache object (contains static data) based on the session id. Once request is received it checks whether cache contains any key for the session id.
- If not available, it will load it from DB and stores it in cache.
- If available it uses that cache and continues with further processing.
Now, with multithreading enabled in this service and when multiple requests (with same session id) are sent to service, all of them are trying to load the data into cache as none of them find that key initially.
Question is: I wanted to stop all the other threads till the first thread loads static data into cache and once first thread is done with loading data in to cache, other threads should use that cache instead of trying to load again.
Looks trivial but somehow not able to think of any multi threading feature which can solve this.
My code looks something like below:
somemethod()
{
if(cache.Contains(someKey)
{
// use cache and do further processing
}
else
{
cache.add(someKey)
}
}