How Does Hibernate Read - Write Cacheconcurrenc Ystrategy Work
How Does Hibernate Read - Write Cacheconcurrenc Ystrategy Work
Vlad Mihalcea
Hibernate
READ_WRITE
CacheConcurrenc
yStrategy work
Find
Last modified: Jan 22, 2019 Article
Follow @vlad_mihalcea
Search …Go
Introduction
In my previous post, I introduced the
NONSTRICT_READ_WRITE second-level cache
concurrency mechanism. In this article, I am going to
continue this topic with the READ_WRITE strategy.
Video
Course
Write-through caching
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Our Cookie Policy Close and accept
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 1/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
NONSTRICT_READ_WRITE
Vlad Mihalcea is a read-through caching
strategy and updates end-up invalidating cache entries. As
simple as this strategy may be, the performance drops
HOME BLOG STORE TRAINING CONSULTING TUTORIALS VIDEOS TALKS
with the increase of write operations. A write-through
cache strategy is better choice for write-intensive
applications, since cache entries can be updated rather
than being discarded.
Hypersistence
Because the database is the system of record and Optimizer
database operations are wrapped inside physical
transactions the cache can either be updated
synchronously (like it’s the case of the TRANSACTIONAL
cache concurrency strategy) or asynchronously (right after
the database transaction is committed).
Inserting data
Because persisted entities are uniquely identified (each
entity being assigned to a distinct database row), the
newly created entities get cached right after the database
transaction is committed:
1 @Override Online
2 public boolean afterInsert( Workshop
3 Object key, Object value, Object vers
4 throws CacheException {
5 region().writeLock( key );
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
6 try {
To find out
7 more, including how to control
final cookies, see
Lockable here: Our
item = Cookie Policy Close and accept
8 (Lockable) region().get( key
9 if ( item == null ) {
10 region().put( key,
11 new Item( value, version,
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 2/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
12 region().nextTimestam Consulting
Vlad13Mihalcea
14 );
)
15 return true;
16 }
HOME 17 BLOG STORE
else { TRAINING CONSULTING TUTORIALS VIDEOS TALKS
18 return false;
19 }
20 }
21 finally {
22 region().writeUnlock( key );
23 }
24 }
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 3/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
Updating data
While inserting entities is a rather simple operation, for
updates, we need to synchronize both the database and
the cache entry. The READ_WRITE concurrency strategy
employs a locking mechanism to ensure data integrity:
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out
1. more, including howTransaction
The Hibernate to control cookies, see here:
commit Our Cookie Policy
procedure Close and accept
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 4/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
6. The ReadWriteEhcacheEntityRegionAccessStrategy
replaces the Lock entry with an actual Item,
encapsulating the entity dissembled state
Deleting data
Deleting entities is similar to the update process, as we
can see from the following sequence diagram:
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Our Cookie Policy Close and accept
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 5/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
Vlad Mihalcea
After
Privacy an entity
& Cookies: Thisissite
deleted, its associated
uses cookies. By continuingsecond-level
to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Our that’s
Cookie Policy Close and accept
cache entry will be replaced by a Lock object,
making any subsequent request to read from the database
instead of using the cache entry.
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 6/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
Vlad Mihalcea
Locking constructs
HOME BLOG STORE TRAINING CONSULTING TUTORIALS VIDEOS TALKS
Both the Item and the Lock classes inherit from the
Lockable type and each of these two has a specific policy
for allowing a cache entry to be read or written.
1 @Override
2 public boolean isReadable(long txTimestam
3 return false;
4 }
5
6 @Override
7 public boolean isWriteable(long txTimesta
8 Object newVersion, Comparator version
9 if ( txTimestamp > timeout ) {
10 // if timedout then allow write
11 return true;
12 }
13 if ( multiplicity > 0 ) {
14 // if still locked then disallow
15 return false;
16 }
17 return version == null
18 ? txTimestamp > unlockTimestamp
19 : versionComparator.compare( vers
20 newVersion ) < 0;
21 }
1 @Override
2 public boolean isReadable(long txTimestam
3 return txTimestamp > timestamp;
4 }
5
6 @Override
7 public boolean isWriteable(long txTimesta
8 Object newVersion, Comparator version
9 return version != null && versionComp
10 .compare( version, newVersion ) <
11 }
Privacy
The&cache
Cookies:entry
This site
is uses
readcookies.
whenBy continuing to use this website, you agree to their use.
the
To find out more, including how to control cookies, see here: Our Cookie Policy Close and accept
ReadWriteEhcacheEntityRegionAccessStrategy get
method is called:
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 8/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
27 )
Vlad28Mihalcea
29
);
return true;
30 }
31 else {
HOME 32 BLOG STORE return
TRAINING
false; CONSULTING TUTORIALS VIDEOS TALKS
33 }
34 }
35 finally {
36 region().writeUnlock( key );
37 }
38 }
Timing out
If the database operation fails, the current cache entry
holds a Lock object and it cannot rollback to its previous
Item state. For this reason, the Lock must timeout to allow
the cache entry to be replaced by an actual Item object.
The EhcacheDataRegion defines the following timeout
property:
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 10/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
HOME 1 properties.put(
BLOG STORE TRAINING CONSULTING TUTORIALS VIDEOS TALKS
2 "net.sf.ehcache.hibernate.cache_lock_t
3 String.valueOf(250));
1 @Override
2 protected Interceptor interceptor() {
3 return new EmptyInterceptor() {
4 @Override
5 public void beforeTransactionComp
6 Transaction tx) {
7 if(applyInterceptor.get()) {
8 tx.rollback();
9 }
10 }
11 };
12 }
1 try {
2 doInTransaction(session -> {
3 Repository repository = (Reposito
4 session.get(Repository.class,
5 repository.setName("High-Performa
6 applyInterceptor.set(true);
7 });
8 } catch (Exception e) {
9 LOGGER.info("Expected", e);
10 }
11 applyInterceptor.set(false);
12
13 AtomicReference<Object> previousCacheEntr
14 new AtomicReference<>();
15 AtomicBoolean cacheEntryChanged = new Ato
16
17 while (!cacheEntryChanged.get()) {
18 doInTransaction(session
Privacy & Cookies: This ->this{ website, you agree to their use.
site uses cookies. By continuing to use
To find19 boolean
out more, including how to control entryChange;
cookies, see here: Our Cookie Policy Close and accept
20 session.get(Repository.class, 1L)
21
22 try {
23 Object previousCacheEntry =
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 11/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
24 previousCacheEntryReferen
Vlad25Mihalcea
26
Object cacheEntry =
getCacheEntry(Repository.
27
28 entryChange = previousCacheEn
HOME 29 BLOG STORE TRAINING CONSULTING
previousCacheEntry != cac TUTORIALS VIDEOS TALKS
30 previousCacheEntryReference.s
31 LOGGER.info("Cache entry {}",
32 ToStringBuilder.reflectio
33 cacheEntry));
34
35 if(!entryChange) {
36 sleep(100);
37 } else {
38 cacheEntryChanged.set(tru
39 }
40 } catch (IllegalAccessException e
41 LOGGER.error("Error accessing
42 }
43 });
44 }
1 select
2 readwritec0_.id as id1_0_0_,
3 readwritec0_.name as name2_0_0_,
4 readwritec0_.version as version3_0_0_
5 from
6 repository readwritec0_
7 where
8 readwritec0_.id=1
9
10 update
11 repository
12 set
13 name='High-Performance Hibernate',
14 version=1
15 where
16 id=1
17 and version=0
18
19 JdbcTransaction - rolled JDBC Connection
20
21 select
22 readwritec0_.id as id1_0_0_,
23 readwritec0_.name as name2_0_0_,
24 readwritec0_.version as version3_0_0_
Privacy25 from
& Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find26 repository
out more, including readwritec0_
how to control cookies, see here: Our Cookie Policy Close and accept
27 where
28 readwritec0_.id = 1
29
30 Cache entry net.sf.ehcache.Element@3f9a08
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 12/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
31 key=ReadWriteCacheConcurrencyStrategy
Vlad32 Mihalcea
33
value=Lock Source-UUID:ac775350-3930-
version=1,
34 hitCount=3,
35 timeToLive=120,
HOME 36 BLOG STORE TRAINING
timeToIdle=120, CONSULTING TUTORIALS VIDEOS TALKS
37 lastUpdateTime=1432280657865,
38 cacheDefaultLifespan=true,id=0
39 ]
40 Wait 100 ms!
41 JdbcTransaction - committed JDBC Connecti
42
43 select
44 readwritec0_.id as id1_0_0_,
45 readwritec0_.name as name2_0_0_,
46 readwritec0_.version as version3_0_0_
47 from
48 repository readwritec0_
49 where
50 readwritec0_.id = 1
51
52 Cache entry net.sf.ehcache.Element@3f9a08
53 key=ReadWriteCacheConcurrencyStrategy
54 value=Lock Source-UUID:ac775350-3930-
55 version=1,
56 hitCount=3,
57 timeToLive=120,
58 timeToIdle=120,
59 lastUpdateTime=1432280657865,
60 cacheDefaultLifespan=true,
61 id=0
62 ]
63 Wait 100 ms!
64 JdbcTransaction - committed JDBC Connecti
65
66 select
67 readwritec0_.id as id1_0_0_,
68 readwritec0_.name as name2_0_0_,
69 readwritec0_.version as version3_0_0_
70 from
71 repository readwritec0_
72 where
73 readwritec0_.id = 1
74 Cache entry net.sf.ehcache.Element@305f03
75 key=ReadWriteCacheConcurrencyStrategy
76 value=org.hibernate.cache.ehcache.int
77 version=1,
78 hitCount=1,
79 timeToLive=120,
80 timeToIdle=120,
81 lastUpdateTime=1432280658322,
Privacy & Cookies: This site cacheDefaultLifespan=true,
82 uses cookies. By continuing to use this website, you agree to their use.
To find83 id=0
out more, including how to control cookies, see here: Our Cookie Policy Close and accept
84 ]
85 JdbcTransaction - committed JDBC Connecti
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 13/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
Conclusion
The READ_WRITE concurrency strategy offers the
benefits of a write-through caching mechanism, but you
need to understand it’s inner workings to decide if it’s good
fit for your current project data access requirements.
Follow @vlad_mihalcea
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 14/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
Vlad Mihalcea
DOWNLOAD NOW
Related
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 15/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
Vlad Mihalcea
Category: Hibernate Tags: caching, concurrency
control, hibernate, read-write, Training, Tutorial
HOME BLOG STORE TRAINING CONSULTING TUTORIALS VIDEOS TALKS
Leave a Reply
Your email address will not be published. Required
fields are marked *
Comment
Name *
Email *
Website
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 16/17
11/6/2020 How does Hibernate READ_WRITE CacheConcurrencyStrategy work - Vlad Mihalcea
Vlad Mihalcea
Powered by WordPress.com.
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Our Cookie Policy Close and accept
https://vladmihalcea.com/how-does-hibernate-read_write-cacheconcurrencystrategy-work/ 17/17