Announcement Announcement Module

Spring Modules forum decommissioned in favor of Spring Extensions

As the Spring Modules project has been replaced by the Spring Extensions ( project, this forum has been decommissioned in favour of Spring Extensions one at:

Please see the Spring Extensions home page for a complete list of current projects in Java, .NET and ActionScript. You can also propose one if you want.

Costin Leau
SpringSource - Spring Training, Consulting, and Support - "From the Source"
See more
See less
Cache and multiple threads Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Cache and multiple threads

    In essence, the AbstractCachingInterceptor.invoke() works like this:

    Object cached = cache.getFromCache(key, model);
    if (null == cached)
    return cachedValueFromSource(mi, key, model);
    return unmaskNull(cached);

    If two threads calls getFromCache() at the same time with the same key and the object is not in the cache yet, it's likely that both threads will proceed and put the results to the cache twice.
    Is this a known issue in the cache module? Synchronize the invoke() method will avoid this issue but it will not scale at all so do not think it's a good idea.
    Looks to me this is a very common issue, yet i do not see a good solution. Are people just ignoring this problem because 1) it will only happen under load. 2) Even if it happens, it's just inefficient, the cache is not corrupted.


  • #2
    You might want to raise an issue on JIRA since synchronization is a big thing and either some code or some documentation has to be updated on this topic.
    I think it depends to some degree what type of cache we are talking about - if it's read-only there is no need for synchronization, if it's read-write then some sort of synchronization has to be in place.
    The cost of it depends again on the load and ofc, the map size.
    One more thing, even when writing is involved, the only thing that might go wrong just by looking at this individual example is returning a stale cache.

    Btw, is the cache object guaranteed to be thread-safe or not?


    • #3
      Thanks Costin for the reply.
      I was actually thinking of the read-only case. However i think the problem is still there. Initially the cache is empty, then two (or more) threads try to get the same object. With any luck, all the threads will end up doing the same computing that the cache tries to avoid in the first place.
      What do you think?


      • #4
        that there are too many ifs and this case has to be tested in the unit tests and clarified by the javadocs/reference documentation.
        Can you please raise an issue on JIRA on this to keep track of it?


        • #5


          • #6
            Thanks. I've just assign it to the current Cache module maintainer.