SlideShare a Scribd company logo
Hibernate
Cache
Alex Verdyan
Why cache?
Why it works?
● Temporal locality
● Non uniform distribution of hits
Temporal locality
Non-uniform distribution
17,000 pageviews
avg load = 250ms
cache 17 pages / 80% of views
cached page load time = 10 ms
new avg load = 58ms
● Trade memory for latency reduction
● Reduce database load
Hibernate cache
● Session level cache - L1
● SessionFactory (JVM) cache - L2
● Query Cache
Session cache - L1
● Enabled by default
● Used transparently during the session
● All objects that was saved or retrieved
○ save
○ update
○ get
○ list
○ iterate
● flush() - will sync cache to DB
● clear() - will evict all objects
L2 cache - configuration
1. Get ehcache.jar and add it to classpath
2.
3. Edit persistence.xml
L2 Cache
● Inter-session cache
● Can be clustered
● Configurable with XML or Annotations
● Divided to regions
○ Entity - data
○ Collections - relations
○ Queries - query results
○ Timestamps - last update timestamp for tables
L2 cache strategies
● Read-only
○ simplest, safest and fastest
○ supports insert, no update/delete
○
● Nonstrict Read-Write
○ occasional writes, no locking cache
○ low prob. that 2 transactions will write the same
object
○ async - update
L2 cache strategies
● Read-Write
○ read committed - transaction isolation
○ uses soft locks
○ async - cache update out of tx
● Transactional
○ only with JTA (i.e. with distributed tx support)
○ serialized transaction isolation
○ sync - cache update inside tx
L2 cache - how it works
● Does not cache actual objects
● Caches values of the properties
● Mappings (relations) are not cached by
default
○ it can helps with N+1 queries
Example
● cache of the mapping is optional
● although it's the best place to improve
● beware of code altering the associations
and not cascading the change
How will the cache look like
*-----------------------------------------------------*
| Person Data Cache |
|-----------------------------------------------------|
| 1 -> [ "John" , "Bon Jovi" , null , [ 2 , 3 ] ] |
| 2 -> [ "Joey" , "Ramone" , 1 , [] ] |
| 3 -> [ "Sara" , "Connor" , 1 , [] ] |
*-----------------------------------------------------*
Hibernate cache stores
"dehydrated" objects
Evicting from cache
From L1 cache (Session)
session.evict(entity)
session.evict(Person.class)
From L2 cache (SessionFactory)
sf.getCache().evictEntity(Person.class,2L);
sf.getCache().
evictCollection("com.bla.Person.children",1L)
Query cache
Query cache
What happens if don't query by Id ?
The query cache will look like:
*---------------------------------------------------------
-*
| Query Cache
|
|---------------------------------------------------------
-|
| ["from Person as p |
Query cache
There are 3 cache regions:
● StandardQueryCache
○ cached query results
● UpdateTimestampsCache
○ holding timestamps of the most recent updates
● NamedQueryCaches
○ Query.setCacheRegion(name)
Query Cache
QC is useful when you query by "Natural id"
Criteria crit = session.createCriteria(Person.class);
crit.add(
Restrictions.
naturalId().
set("email", "joey@ramones.com")).
setCacheable(true).
uniqueResult();
Since Natural Id immutable, Natural Id -> Primary Key
mapping cannot be invalidated
This allows Hibernate to bypass UpdateTimestampCache
Query Cache - Pitfalls
● Any update to the underlying table updates the
timestamp cache - invalidates all entities
● Memory
○ the queries are large pretty strings and the
bind variables can be objects
● Lock contention - QC has a coarse lock on
timestamp cache for insert/update/delete and
lookups
Stuff to remember
● Cache cannot know about updates made to
the persistent store by another application
● Query cache - unless you use a natural key
is almost always a bad idea
○ unless you know what you're turning it on
○ you can show an improvement with realistic load
● TTL and TTI
○ tune them
Cache providers
Bundled cache providers
Cache Type Cluster Safe Query Cache Supported
ConcurrentHashMap memory no yes
EHCache memory, disk,
transactional, clustered
yes yes
Infinispan (JBoss Cache) clustered (ip multicast),
transactional
yes yes (clock sync req.)
Bundled cache providers
Cache read-only nonstrict-read-write read-write transactional
ConcurrentHashMap yes yes yes
EHCache yes yes yes yes
Infinispan (JBoss cache) yes yes
More cache providers
● Hazelcast
● GemFire
● Oracle Coherence
● Gigaspaces
Monitoring
Questions
References
http://tech.puredanger.com/2009/07/10/hibernate-
query-cache/
http://anirbanchowdhury.wordpress.
com/2012/07/23/hibernate-second-level-cache-
ehcache/#introduction
http://www.javalobby.org/java/forums/t48846.html
http://www.slideshare.net/alexmiller/cold-hard-cache

More Related Content

PDF
New availability features in oracle rac 12c release 2 anair ss
PDF
LMAX Architecture
PDF
Best practices for MySQL High Availability Tutorial
PDF
Module 2 - Datalake
PPTX
Understand oracle real application cluster
PDF
Enterprise manager 13c
PDF
Oracle RDBMS architecture
PPTX
Vert.x for Microservices Architecture
New availability features in oracle rac 12c release 2 anair ss
LMAX Architecture
Best practices for MySQL High Availability Tutorial
Module 2 - Datalake
Understand oracle real application cluster
Enterprise manager 13c
Oracle RDBMS architecture
Vert.x for Microservices Architecture

What's hot (20)

PDF
Oracle Enterprise Manager Cloud Control 13c for DBAs
PPTX
Introduction to DDD
PDF
Logstash-Elasticsearch-Kibana
PDF
Process Scheduling Algorithms.pdf
PPTX
Basic oracle-database-administration
PPTX
Key-Value NoSQL Database
PPTX
Gremlin's Anatomy
PPTX
HDFS Tiered Storage: Mounting Object Stores in HDFS
PPTX
Elastic - ELK, Logstash & Kibana
PDF
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...
PDF
TFA Collector - what can one do with it
PPTX
Reshape Data Lake (as of 2020.07)
PDF
Extending Spark With Java Agent (handout)
ZIP
NoSQL databases
PPTX
HBase and HDFS: Understanding FileSystem Usage in HBase
PDF
pstack, truss etc to understand deeper issues in Oracle database
PDF
A Thorough Comparison of Delta Lake, Iceberg and Hudi
PDF
AWR Ambiguity: Performance reasoning when the numbers don't add up
PPTX
Log management with ELK
Oracle Enterprise Manager Cloud Control 13c for DBAs
Introduction to DDD
Logstash-Elasticsearch-Kibana
Process Scheduling Algorithms.pdf
Basic oracle-database-administration
Key-Value NoSQL Database
Gremlin's Anatomy
HDFS Tiered Storage: Mounting Object Stores in HDFS
Elastic - ELK, Logstash & Kibana
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...
TFA Collector - what can one do with it
Reshape Data Lake (as of 2020.07)
Extending Spark With Java Agent (handout)
NoSQL databases
HBase and HDFS: Understanding FileSystem Usage in HBase
pstack, truss etc to understand deeper issues in Oracle database
A Thorough Comparison of Delta Lake, Iceberg and Hudi
AWR Ambiguity: Performance reasoning when the numbers don't add up
Log management with ELK
Ad

Viewers also liked (20)

PDF
טלפונים חכמים ואתם
PPTX
1953 and all that. A tale of two sciences (Kitcher, 1984)
PDF
Guice - dependency injection framework
PDF
מכתב המלצה - לירן פרידמן
PDF
Responsive Web Design
PDF
Work-for-hire Game Studios: Elevate Your Game
PDF
Dynamo and BigTable - Review and Comparison
PDF
What is exactly anti fragile in dev ops - v3
PPTX
JavaScript TDD
DOCX
HagayOnn_EnglishCV_ 2016
PPTX
Orchestration tool roundup - OpenStack Israel summit - kubernetes vs. docker...
PDF
Elasticsearch na prática
PPTX
Scala does the Catwalk
PPTX
Not your dad's h base new
PDF
What's the Magic in LinkedIn?
PDF
Scrum. software engineering seminar
PDF
Storm at Forter
PPTX
Joy of scala
PDF
Code quality as a built-in process
PDF
How does the Internet Work?
טלפונים חכמים ואתם
1953 and all that. A tale of two sciences (Kitcher, 1984)
Guice - dependency injection framework
מכתב המלצה - לירן פרידמן
Responsive Web Design
Work-for-hire Game Studios: Elevate Your Game
Dynamo and BigTable - Review and Comparison
What is exactly anti fragile in dev ops - v3
JavaScript TDD
HagayOnn_EnglishCV_ 2016
Orchestration tool roundup - OpenStack Israel summit - kubernetes vs. docker...
Elasticsearch na prática
Scala does the Catwalk
Not your dad's h base new
What's the Magic in LinkedIn?
Scrum. software engineering seminar
Storm at Forter
Joy of scala
Code quality as a built-in process
How does the Internet Work?
Ad

Similar to Hibernate caching (20)

DOC
Advanced Hibernate Notes
PPT
Hibernate caching
PPT
Hibernate jj
PDF
Hibernate ORM: Tips, Tricks, and Performance Techniques
PDF
Advance Features of Hibernate
PPT
13 caching latest
PDF
Hibernate performance tuning
PPTX
Hibernate Performance Tuning @JUG Thüringen
PDF
ORM and distributed caching
PPT
Advanced Hibernate
PPTX
Session 40 - Hibernate - Part 2
DOC
Hibernate tutorial for beginners
PPSX
Hibernate - Part 2
PPTX
Hibernate - KNOWARTH
PPT
Hibernate for Beginners
PPT
10 Cache Implementation
PPTX
Session 39 - Hibernate - Part 1
PDF
Hibernate 3
Advanced Hibernate Notes
Hibernate caching
Hibernate jj
Hibernate ORM: Tips, Tricks, and Performance Techniques
Advance Features of Hibernate
13 caching latest
Hibernate performance tuning
Hibernate Performance Tuning @JUG Thüringen
ORM and distributed caching
Advanced Hibernate
Session 40 - Hibernate - Part 2
Hibernate tutorial for beginners
Hibernate - Part 2
Hibernate - KNOWARTH
Hibernate for Beginners
10 Cache Implementation
Session 39 - Hibernate - Part 1
Hibernate 3

Recently uploaded (20)

PPTX
Machine Learning_overview_presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Cloud computing and distributed systems.
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Spectroscopy.pptx food analysis technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Programs and apps: productivity, graphics, security and other tools
Machine Learning_overview_presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Cloud computing and distributed systems.
A comparative analysis of optical character recognition models for extracting...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
MIND Revenue Release Quarter 2 2025 Press Release
“AI and Expert System Decision Support & Business Intelligence Systems”
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation theory and applications.pdf
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25-Week II
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Encapsulation_ Review paper, used for researhc scholars
Spectroscopy.pptx food analysis technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Programs and apps: productivity, graphics, security and other tools

Hibernate caching

  • 2. Why cache? Why it works? ● Temporal locality ● Non uniform distribution of hits
  • 5. 17,000 pageviews avg load = 250ms cache 17 pages / 80% of views cached page load time = 10 ms new avg load = 58ms ● Trade memory for latency reduction ● Reduce database load
  • 6. Hibernate cache ● Session level cache - L1 ● SessionFactory (JVM) cache - L2 ● Query Cache
  • 7. Session cache - L1 ● Enabled by default ● Used transparently during the session ● All objects that was saved or retrieved ○ save ○ update ○ get ○ list ○ iterate ● flush() - will sync cache to DB ● clear() - will evict all objects
  • 8. L2 cache - configuration 1. Get ehcache.jar and add it to classpath 2. 3. Edit persistence.xml
  • 9. L2 Cache ● Inter-session cache ● Can be clustered ● Configurable with XML or Annotations ● Divided to regions ○ Entity - data ○ Collections - relations ○ Queries - query results ○ Timestamps - last update timestamp for tables
  • 10. L2 cache strategies ● Read-only ○ simplest, safest and fastest ○ supports insert, no update/delete ○ ● Nonstrict Read-Write ○ occasional writes, no locking cache ○ low prob. that 2 transactions will write the same object ○ async - update
  • 11. L2 cache strategies ● Read-Write ○ read committed - transaction isolation ○ uses soft locks ○ async - cache update out of tx ● Transactional ○ only with JTA (i.e. with distributed tx support) ○ serialized transaction isolation ○ sync - cache update inside tx
  • 12. L2 cache - how it works ● Does not cache actual objects ● Caches values of the properties ● Mappings (relations) are not cached by default ○ it can helps with N+1 queries
  • 13. Example ● cache of the mapping is optional ● although it's the best place to improve ● beware of code altering the associations and not cascading the change
  • 14. How will the cache look like *-----------------------------------------------------* | Person Data Cache | |-----------------------------------------------------| | 1 -> [ "John" , "Bon Jovi" , null , [ 2 , 3 ] ] | | 2 -> [ "Joey" , "Ramone" , 1 , [] ] | | 3 -> [ "Sara" , "Connor" , 1 , [] ] | *-----------------------------------------------------* Hibernate cache stores "dehydrated" objects
  • 15. Evicting from cache From L1 cache (Session) session.evict(entity) session.evict(Person.class) From L2 cache (SessionFactory) sf.getCache().evictEntity(Person.class,2L); sf.getCache(). evictCollection("com.bla.Person.children",1L)
  • 17. Query cache What happens if don't query by Id ? The query cache will look like: *--------------------------------------------------------- -* | Query Cache | |--------------------------------------------------------- -| | ["from Person as p |
  • 18. Query cache There are 3 cache regions: ● StandardQueryCache ○ cached query results ● UpdateTimestampsCache ○ holding timestamps of the most recent updates ● NamedQueryCaches ○ Query.setCacheRegion(name)
  • 19. Query Cache QC is useful when you query by "Natural id" Criteria crit = session.createCriteria(Person.class); crit.add( Restrictions. naturalId(). set("email", "joey@ramones.com")). setCacheable(true). uniqueResult(); Since Natural Id immutable, Natural Id -> Primary Key mapping cannot be invalidated This allows Hibernate to bypass UpdateTimestampCache
  • 20. Query Cache - Pitfalls ● Any update to the underlying table updates the timestamp cache - invalidates all entities ● Memory ○ the queries are large pretty strings and the bind variables can be objects ● Lock contention - QC has a coarse lock on timestamp cache for insert/update/delete and lookups
  • 21. Stuff to remember ● Cache cannot know about updates made to the persistent store by another application ● Query cache - unless you use a natural key is almost always a bad idea ○ unless you know what you're turning it on ○ you can show an improvement with realistic load ● TTL and TTI ○ tune them
  • 23. Bundled cache providers Cache Type Cluster Safe Query Cache Supported ConcurrentHashMap memory no yes EHCache memory, disk, transactional, clustered yes yes Infinispan (JBoss Cache) clustered (ip multicast), transactional yes yes (clock sync req.)
  • 24. Bundled cache providers Cache read-only nonstrict-read-write read-write transactional ConcurrentHashMap yes yes yes EHCache yes yes yes yes Infinispan (JBoss cache) yes yes
  • 25. More cache providers ● Hazelcast ● GemFire ● Oracle Coherence ● Gigaspaces