Hibernate second level cache - The Timestamp region

If you are not familiar with Hibernate second level cache internal implementation than I suggest that you will read the following link before continue reading.The follwoing link should do you introduction with Hibernate cache regions, Hibernate cache associations, How Hibernate store Objects in cache.

UpdateTimestamsCache region is not cover in the previoues link , so we are going to duscess it in this post.
UpdateTimestamsCache store the last time that a table was written. This data is imporatnt in order to prevent stale data.

Details on the UpdateTimestamsCache regioncan be found in the following link -  http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/11/09/first-and-second-level-caching-in-nhibernate.aspx .

Now, when we come to actually using the cache, we should be aware to few things:
1.         Each session is associated with a timestamp on creation.
2.         Every time we put query results in the cache, the timestamp of the executing session is recorded.

3.         The timestamp cache is updated whenever a table is written to, but in a tricky sort of way:
When we perform the actual writing, we write a value that is somewhere in the future to the cache. So all queries that hit the cache now will not find it, and then hit the DB to get the new data. Since we are in the middle of transaction, they would wait until we finish the transaction. If we are using low isolation level, and another thread / machine attempts to put the old results back in the cache, it wouldn't hold, because the update timestamp is into the future.

When we perform the commit on the transaction, we update the timestamp cache with the current value.

Now, let us think about the meaning of this, shall we?

If a session has performed an update to a table, committed the transaction and then executed a cache query, it is not valid for the cache. That is because the timestamp written to the update cache is the transaction commit timestamp, while the query timestamp is the session's timestamp, which obviously comes earlier.

The update timestamp cache is not updated until you commit the transaction! This is to ensure that you will not read "uncommitted values" from the cache.

Please note that if you open a session with your own connection, it will not be able to put anything in the cache (all its cached queries will have an invalid timestamp!)

In general, those are not things that you need to concern yourself with, but I spent some time today just trying to get tests for the second level caching working, and it took me time to realize that in the tests I didn't used transactions and I used the same session for querying as for performing the updates.

אין תגובות:

הוסף רשומת תגובה