EhCache3 as JCache (JSR-107) Implementation with Cache Statistics
If you are reading this you already know that caching is mechanism to store static data In-Memory for faster access and avoid expensive database calls or any kind of service calls to get the data.
Read my other post to learn InMemory Caching using EhCache3.
There are many ways to implement cache in java based applications, starting from very simple Map
About JCache
Some of the implementations are -
For comprehensive list of JCache implementations click here
Subtle Benefits
- Irrespective of what implementation you choose you will always use classes and interfaces provided by jcache api. Which means you can change underlying implementation anytime
- If you upgrade underlying implementation it should not be breaking your existing code
- Access live cache usage statistics at runtime using JMX
- You are using Standard API Specification :-)
JCache with EhCache as Implementation
Item Expiry - If entry in the cache meets the expiry condition, it will be evicted (removed) from the cache. To standard type of expiry conditions are Time-To-Live and Time-To-Idle. I will use Time-To-Live
Cache Max Size - Maximum size up to which the cache can grow. The max size constraint can be set by byte size (KB, MB etc) or no on entries in the cache. I will use no of entries.
Cache Usage Statistics - When you implement caching you are certainly interested in knowing cache usage statistics like, cache hits, misses, no of time cache was accessed etc. With JCache you can get all cache usage statistics live at runtime using JMX mechanism.
Cache manager helper class which takes care of initializing cache and implements some utility method to easily access cache and cache usage statistics
Output
Cache Initialized
Entries in the Cache at: Tue Jan 09 22:10:01 EST 2018
--------------------
Key: 1, Value: null
Key: 2, Value: null
Key: 3, Value: Person [personId=3, firstName=firstName-1, lastName=lastName-3]
Key: 4, Value: Person [personId=4, firstName=firstName-1, lastName=lastName-4]
Key: 5, Value: Person [personId=5, firstName=firstName-1, lastName=lastName-5]
Key: 6, Value: Person [personId=6, firstName=firstName-1, lastName=lastName-6]
Key: 7, Value: Person [personId=7, firstName=firstName-1, lastName=lastName-7]
Waiting for 40 seconds
After 40 seconds wait
Entries in the Cache at: Tue Jan 09 22:10:41 EST 2018
--------------------
Key: 1, Value: null
Key: 2, Value: null
Key: 3, Value: null
Key: 4, Value: null
Key: 5, Value: null
Key: 6, Value: null
Key: 7, Value: null
Cache Usage Statitics
--------------------
CacheHits=5
CacheHitPercentage=35.714287
CacheMisses=9
CacheMissPercentage=64.28571
CacheGets=14
CachePuts=7
CacheRemovals=0
CacheEvictions=2
AverageGetTime=91.180786
AveragePutTime=731.2153
AverageRemoveTime=0.0
Comments
Post a Comment