A colleague of mine and I have been having a debate as to when (if?) a collection cached in the second level cache can return stale data (we're using ehcache and hibernate 3.2.4 ).
Here's the scenario:
- parent object P is cached and is an entity.
- Parent has a collection (bag) of children which are cached and lazy.
- Children objects C are cached and are entities.
- We are using Nonstrict read-write as our cache concurrency strategy for all of these.
- Our session factory is process scoped and only 1 JVM is involved.
- Assume that the cache regions for all caches above are large enough to hold all instances of all children and parents in memory easily.
At time T1: Load parent P and children C1...CN by performing a session.load(p) and iterating over the children collection so that all C1...CN are loaded.
At time T2: Another session loads C1 and updates C1 changing some of its data.
Under what circumstances can I call P.getChildren().get(0) and a stale version of C1 (the version of C1 loaded at time T1) will be returned?
I'm thinking there are two :
- If I'm in the same hibernate session as the operations in T1 (in which case the session cached version is returned)
- With non-strict read write, it would be possible to have a race condition where the update at T2 and the load occur at almost the same time and the load wins the race and retrieves the stale object from the cache. (In which case I can change to read-write and I'll be ok)