简体   繁体   中英

how first level cache works, if we have multiple session objects?

I have a question regarding 1st level and 2nd level caches.

2nd level cache

It is associated with the sessionFactory. Suppose we have two sessions session1 and session2 and have one table student . We called get() from session1 , then it will hit DB and store the object in session1 and in the sessionFactory. if we called get() from session2 , then sessionFacory object will copied to session2. If in future we call get() it will not hit DB. It will take it from session objects(1st level cache).

Upto this I am clear.

After that another session called session3 want to update the same record, then if we call get() on session1 and session2 . what will happen?

1st level cache

It is associated with a session. If we have two sessions session1 and session2 . We called get() from session1 , it will hit DB and store the object in session1. If we update using session2 , what will happen if we call get() next time from session1 ?

I heard 2nd level cache has some disadvantages. If this is true what are they?

You are asking three questions at once.

1. Question

I'm not sure what you mean by

session3 want to update the same record

Sessions don't have free will. And if they had just from wanting something pretty much nothing happens. But if you use a third session to update the entities already cached in session1 and session2 they will keep there cached (now outdated) version. If you use session1 or session2 to update the same entity, the update will fail with an optimistic locking exception.

The 2nd level cache will get updated with the new version stored by session3 though.

2. Question

This is the same as the first scenario: session1 now has a stale object which it will continue to use.

3. Questions (Drawbacks of the 2nd level cache)

All kinds of caches have the same challanges:

  1. If you put stuff into cache but don't need it again you are wasting CPU time for putting it there and memory for keeping it there.

  2. If you look into a cache but don't find what you are looking for you are wasting CPU time for looking there.

  3. If you keep stuff in a cache after it changed, you will work with stale data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM