Java.Hibernate.Middle.How Hibernate invalidates cache in case of read-write strategy ?

Short Answer

In READ_WRITE strategy, Hibernate uses a mechanism called cache invalidation: when an entity is updated or deleted, it evicts the corresponding cached entry, marking it stale so it can’t be served until reloaded from the database.


🔎 Detailed Explanation

🔹 When an entity using READ_WRITE caching is modified:
1️⃣ Hibernate marks the corresponding cache entry as invalid immediately upon update or delete.
2️⃣ Other sessions trying to read the same entity won’t get stale data from cache, because the entry has been evicted or locked.
3️⃣ The next time the entity is accessed, Hibernate reloads it from the database and puts the fresh value back into the cache.

🔹 This happens within the transaction boundaries:
✅ The cache update or invalidation is coordinated with the database transaction, ensuring data consistency.
✅ If the transaction rolls back, Hibernate keeps the old cache entry (since the DB hasn’t changed).


🔹 How does it actually work?

  • Hibernate uses a soft-lock mechanism:
    • When an update starts, it places a soft lock on the cache entry → signals other transactions not to read it until update finishes.
    • When the transaction commits, Hibernate evicts or updates the cache entry with the new state.
    • If the transaction rolls back, the cache entry remains unchanged.

🧑‍💻 Illustrative Flow

Session 1: Updates entity → cache entry is locked → DB updated → transaction commits → cache entry evicted/updated.
Session 2: Reads entity → sees lock → waits or reloads from DB → gets fresh value.

🔹 Important Consequences
✅ Prevents stale data from being served during concurrent updates.
✅ Guarantees cache consistency with database state in read-write scenarios.
❌ Comes with performance cost due to locking and cache updates → that’s the trade-off vs. READ_ONLY.

📌 Key Takeaways

✅ In READ_WRITE strategy, Hibernate invalidates or updates cache entries in sync with DB transactions.
✅ Hibernate uses soft locks to prevent concurrent sessions from seeing inconsistent data.
✅ This mechanism ensures safe caching of mutable data, avoiding stale reads.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.