You are on page 1of 14

JAVA CACHING CHEATSHEET

Java Caching Cheatsheet


TABLE OF CONTENTS

Preface 1
Introduction 1
The JCache API (JSR 107) 1
JCache "Hello World" 2
Cache 3
CacheManager 3
CachingProvider 4
Caching 5
Configuration 5
Expiry Policy 6
Listeners and Listener Filters 6
Cache Entry Listeners. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Cache Manager Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Listener Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Loaders and Writers 8
Cache Loaders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Cache Writers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Cache Entry Processors 9
Annotations 9
Monitoring And Management 10
Management and Monitoring Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
JMX API for JCache Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Vendor Specific Features 11
Cache Topologies And Modes 12
Resources 12

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


1 JAVA CACHING CHEATSHEET

PREFACE
PREFACE applications by simply annotating methods
with caching annotations like @Cacheable,
Welcome to the Java Caching Cheatsheet! Caching @CachePut, and @CacheEvict to control caching
plays a crucial role in improving application behavior at the method level.
performance, scalability, and reliability by storing
• HTTP Caching: For web applications, Java
frequently accessed data in memory for fast
supports HTTP caching mechanisms using
retrieval. Whether you’re a developer, architect, or
headers like Cache-Control and ETag. These
system administrator, understanding caching
headers enable browsers and web servers to
concepts, strategies, and best practices is essential
cache resources like images, stylesheets, and
for building efficient and responsive applications.
scripts, reducing the need to re-download them
on subsequent requests.
This cheatsheet provides a comprehensive
overview of caching systems, covering topics such • Database Caching: Caching can be applied at
as cache topologies, implementation strategies, the database level to store frequently accessed
management, and monitoring. Whether you’re new query results. Java applications often leverage
to caching or looking to deepen your knowledge, technologies like Hibernate for object-relational
this cheatsheet serves as a handy reference for mapping, which includes caching capabilities.
mastering caching fundamentals and optimizing
your Java applications. Java caching plays a crucial role in optimizing
application performance, especially in scenarios
INTRODUCTION
INTRODUCTION
where data retrieval or computation is resource-
intensive. It is essential to carefully design and
Java caching is a technique used to store and configure caching strategies based on the specific
manage frequently accessed data in a temporary requirements of the application to strike a balance
storage area, known as a cache, to improve between improved performance and efficient
application performance. Caching helps reduce the resource utilization.
time and resources needed to fetch or compute data
by keeping a copy readily available. THEJCACHE
THE JCACHEAPI
API(JSR
(JSR107)
107)

In Java, caching can be implemented at various JSR-107, commonly known as JCache, is a Java
levels, including: specification for a caching API and standardizing
caching annotations. The goal of JCache is to
• Memory Caching: Java provides in-memory provide a common way for Java applications to
caching mechanisms using data structures like interact with caching systems, fostering portability
HashMap or specialized libraries like Guava across different caching providers like the ones
Cache or Caffeine. These allow developers to mentioned above.
store key-value pairs in memory, making data
retrieval faster than fetching from the original Key features of JCache include:
source.
• API Standardization: JCache defines a set of
• Distributed Caching: In distributed systems,
standard interfaces and classes for interacting
caching can be extended across multiple nodes
with caches. It is not tied to a specific caching
to share cached data. Libraries and platforms
implementation. Instead, it allows for the
like Ehcache, Apache Ignite, Oracle Coherence,
integration of multiple caching providers that
Infinispan, VMware GemFire, or Redis provide
adhere to the specification.
distributed caching solutions, enabling efficient
sharing of cached data among different • Annotations: JCache introduces annotations
instances of an application. such as @CacheResult, @CachePut, and
@CacheRemove that can be used to control
• Application-Level Caching: Many Java
caching behavior in a declarative manner.
frameworks and libraries offer built-in caching
These annotations are similar to those found in
mechanisms. Spring, for example, provides a
frameworks like Spring.
comprehensive caching abstraction that allows
developers to easily integrate caching into their • Basic Caching Operations: JCache supports

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


2 JAVA CACHING CHEATSHEET

fundamental caching operations, including <groupId>


putting, getting, and removing entries from the org.ehcache</groupId>
cache. It provides a standardized way to <artifactId>
perform these operations regardless of the ehcache</artifactId>
underlying caching provider. <version>3.9.6</version>
• Configuration: The specification defines a </dependency>
standardized way to configure caching settings, </dependencies>
such as cache size, eviction policies, and
expiration times. This makes it easier to
manage and tune caching behavior across The following example sets up a cache, puts a
different implementations. "Hello, World!" greeting into the cache, retrieves it,
and prints it to the console.
• Integration with Java EE and SE: JCache is
designed to seamlessly integrate with both Java
EE (Enterprise Edition) and Java SE (Standard import javax.cache.Cache;
Edition) environments. This ensures that import javax.cache.CacheManager;
applications can use the same caching API import javax.cache.Caching;
across different Java platforms.
import
javax.cache.configuration.MutableCon
Using a standard API, like JCache, enables
developers to switch between different caching
figuration;
implementations and choose the caching solution
that best fits their needs with minimal to no code public class HelloWorldJCache {
changes in their application. Furthermore it boosts
productivity because it ensures that the learning public static void main(String[]
curve is smaller since it is restricted to the args) {
knowledge of JCache as a standard and not the // Create a CacheManager
specifics of each vendor implementation. CacheManager cacheManager =
Caching.getCachingProvider().getCach
JCACHE"HELLO
JCACHE "HELLOWORLD"
WORLD" eManager();

To create a simple "Hello World" example using


// Define cache
JCache, you’ll first need to include the JCache API
configuration
and a specific caching provider in your project.
Let’s use Ehcache as the caching provider in this
MutableConfiguration<String,
example. If you’re using Maven, include the String> cacheConfig = new
following dependencies in your pom.xml MutableConfiguration<>();
cacheConfig.setStoreByValue
(false); // Store values by
<dependencies> reference
<!-- JCache API --> cacheConfig.setTypes(String
<dependency> .class, String.class);
<groupId> cacheConfig
javax.cache</groupId> .setExpiryPolicyFactory(CreatedExpir
<artifactId>cache- yPolicy.factoryOf(Duration.ONE_MINUT
api</artifactId> E));
<version>1.1.1</version> cacheConfig
</dependency> .setManagementEnabled(true);
cacheConfig
<!-- Ehcache as the caching .setStatisticsEnabled(true);
provider -->
<dependency> // Create a cache

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


3 JAVA CACHING CHEATSHEET

Cache<String, String> cache Method Description


= cacheManager.createCache V getAndPut(K key, V Retrieves the current
("helloCache", cacheConfig); value) value associated with
the specified key, then
// Put data into the cache updates the value with
cache.put("greeting", the new one.
"Hello, World!"); void remove(K key) Removes the entry for
the specified key from
// Get data from the cache the cache, if present.
String greeting = cache.get
boolean remove(K key, V Removes the entry for
("greeting"); oldValue) the specified key from
System.out.println(
the cache only if it is
greeting); currently mapped to the
specified value.
// Close the CacheManager
void removeAll(Set<? Removes entries for
when done extends K> keys) multiple keys from the
cacheManager.close();
cache.
}
void removeAll() Removes all entries
}
from the cache.
void putAll(Map<? Associates multiple key-
CACHE
CACHE extends K, ? extends V> value pairs with the
entries)
cache.
The javax.cache.Cache interface is a fundamental
boolean putIfAbsent(K Associates the specified
part of the Java Caching API. It represents a cache, key, V value) value with the specified
which is a temporary storage area for key-value
key in the cache if the
pairs where data can be stored and retrieved
specified key is not
quickly. It provides methods for storing, retrieving,
already associated with
and manipulating cached data. It abstracts the
a value.
underlying caching implementation, allowing
developers to interact with different caching void clear() Clears the cache,
providers through a common interface. removing all entries.
void close() Closes the cache,
Following is a table listing some of the most
releasing any resources
commonly used methods of the javax.cache.Cache
associated with it.
interface.

These methods provide basic functionality for


Method Description
interacting with cached data, allowing developers
V get(K key) Retrieves the value to manage cached entries efficiently within their
associated with the applications.
specified key from the
cache, or null if the key CACHEMANAGER
CACHEMANAGER
is not found.
void put(K key, V Associates the specified The javax.cache.CacheManager interface is
value) value with the specified responsible for managing caches and their
key in the cache. configurations within a caching environment. It
provides methods to create, retrieve, and manage
boolean containsKey(K Checks if the cache
key) caches, as well as access caching-specific features
contains an entry for the
such as configuration and statistics.
specified key.

Following is a table listing some of the most

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


4 JAVA CACHING CHEATSHEET

commonly used methods of the Method Description


javax.cache.CacheManager interface.
Properties Retrieves the properties
getProperties() used to initialize this
Method Description
CacheManager.
CachingProvider Retrieves the
getCachingProvider() CachingProvider These methods provide essential functionality for
associated with this managing caches and their configurations within a
CacheManager. caching environment. Developers can use these
void close() Closes this CacheManager methods to create, access, and configure caches as
and releases any needed for their applications.
resources associated
with it. CACHINGPROVIDER
CACHINGPROVIDER
void Destroys the cache
destroyCache(String The javax.cache.spi.CachingProvider interface
specified by its name.
cacheName) serves as a factory for creating and accessing
boolean isClosed() caching-related entities such as CacheManager
Checks if this
instances. It acts as an abstraction layer between
CacheManager is closed.
the application and the underlying caching
boolean Checks if the specified implementation.
isSupported(OptionalFea optional feature is
ture feature)
supported by this Below is a table listing some of the most commonly
CacheManager. used methods of the
void javax.cache.spi.CachingProvider interface.
Enables or disables
enableManagement(String management (statistics
cacheName, boolean Method Description
enabled) and monitoring) for the
cache specified by its CacheManager Retrieves the default
name. getCacheManager() CacheManager associated
void Enables or disables with this
enableStatistics(String statistics collection for CachingProvider.
cacheName, boolean
enabled) the cache specified by its boolean Checks if the specified
name. isSupported(OptionalFea optional feature is
ture feature)
void createCache(String Creates a cache with the supported by this
cacheName, specified name and CachingProvider.
Configuration<K,V>
configuration) configuration. void close() Closes this
CachingProvider and
void Destroys the cache
destroyCache(String releases any resources
specified by its name.
cacheName) associated with it.
C getCache(String Retrieves a cache by its String getDefaultURI() Retrieves the default
cacheName, Class<K> name, specifying key URI of this
keyType, Class<V>
valueType) and value types. CachingProvider.

Iterable<String> Properties Retrieves the default


Retrieves an iterable
getCacheNames() getDefaultProperties() properties used to
collection of cache
names managed by this configure this
CacheManager. CachingProvider.

ClassLoader Retrieves the


getClassLoader() These methods enable developers to manage
ClassLoader used by
caching providers, create cache managers, and
caches managed by this
configure caching behavior within their
CacheManager.
applications. They provide flexibility in handling
caching-related tasks while abstracting the

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


5 JAVA CACHING CHEATSHEET

underlying caching implementation details. javax.cache.configuration.MutableConfiguration


provides a mutable implementation of the
CACHING
CACHING Configuration interface. It allows developers to
modify caching settings such as expiry policies, size
javax.cache.Caching is a utility class that serves as limits, listeners, and statistics collection during
the entry point for accessing caching functionality runtime.
within Java applications. It provides static methods
to create and access caching providers and cache Below’s a table listing some of the most commonly
managers. It abstracts the process of obtaining used methods of the
caching-related entities, making it easier for javax.cache.configuration.MutableConfiguration
developers to integrate caching functionality into class along with their descriptions.
their applications.
Method Description
Here’s a table listing some of the most commonly MutableConfiguration(Cl Constructs a new
used methods of the javax.cache.Caching class along ass<K> keyType, MutableConfiguration
with their descriptions. Class<V> valueType)
with the specified key
and value types.
Method Description
setStoreByValue(boolean Sets whether the cache
CachingProvider Retrieves the default isStoreByValue) should store values by
getCachingProvider() caching provider. value or by reference.
CacheManager Retrieves the default setTypes(Class<K> Sets the key and value
getCacheManager() cache manager. keyType, Class<V> types for the cache.
valueType)
void Closes the specified
closeCacheManager(Cache cache manager. setExpiryPolicyFactory( Sets the factory for
Manager cacheManager) Factory<? extends creating expiry policies
ExpiryPolicy> factory)
Iterable<CachingProvide Retrieves an iterable for cache entries.
r> collection of all setStatisticsEnabled(bo Sets whether statistics
getCachingProviders()
registered caching olean collection is enabled for
providers. isStatisticsEnabled)
the cache.
Iterable<CacheManager> Retrieves an iterable setManagementEnabled(bo Sets whether
getCacheManagers(Cachin collection of cache olean
gProvider management
managers associated isManagementEnabled)
cachingProvider) (monitoring and
with the specified configuration) is
caching provider. enabled for the cache.
addCacheEntryListenerCo Adds a cache entry
These methods provide convenient ways to obtain nfiguration(CacheEntryL listener configuration to
caching providers and cache managers, enabling istenerConfiguration<K,
the cache.
developers to effectively manage caching V>
functionality within their applications. listenerConfiguration)
removeCacheEntryListene Removes a cache entry
CONFIGURATION
CONFIGURATION
rConfiguration(CacheEnt listener configuration
ryListenerConfiguration
<K, V> from the cache.
The javax.cache.configuration package contains listenerConfiguration)
classes and interfaces for configuring caches and
setCacheWriterConfigura Sets the cache writer
cache managers in Java applications. These classes tion(CacheWriterConfigu configuration for the
and interfaces allow developers to define and ration<K, V>
customize various aspects of caching behavior, cacheWriterConfiguratio cache.
n)
such as event listeners, cache loaders/writers, and
statistics collection. In general, it provides a flexible
way to define caching behavior and settings
according to specific application requirements.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


6 JAVA CACHING CHEATSHEET

Method Description ExpiryPolicy Description


setCacheLoaderConfigura Sets the cache loader Implementation
tion(CacheLoaderConfigu configuration for the EternalExpiryPolicy Indicates that cached
ration<K, V>
cacheLoaderConfiguratio cache. entries never expire.
n) Entries remain in the
cache indefinitely until
setReadThrough(boolean Sets whether the cache
isReadThrough) explicitly removed.
should read through to a
cache loader if a value is ModifiedExpiryPolicy Expires entries based on
not found in the cache. their modification time.
When an entry is
setWriteThrough(boolean Sets whether the cache
isWriteThrough) updated, its expiration
should write through to
time is extended by a
a cache writer.
fixed duration from the
last update.
EXPIRYPOLICY
EXPIRY POLICY
These ExpiryPolicy implementations offer different
The javax.cache.expiry.ExpiryPolicy is an interface
strategies for determining the expiration time of
that defines the expiration policy for cached cached entries based on factors such as access time,
entries. It specifies how long an entry should creation time, modification time, or an eternal
remain valid in the cache before it is considered policy where entries never expire. Developers can
expired and potentially evicted from the cache. choose the appropriate implementation based on
ExpiryPolicy allows developers to specify different their caching requirements and desired eviction
expiration policies based on various criteria such as behavior.
creation time, last access time, or a combination of
both. By default, the entries in a javax.cache.Cache In addition to the aforementioned policies, JCache
do not expire. allows you to implement custom eviction policies
by implementing the
Below is a table listing some of the most common javax.cache.expiry.ExpiryPolicy interface.
implementations of the
javax.cache.expiry.ExpiryPolicy interface along LISTENERSAND
LISTENERS ANDLISTENER
LISTENERFILTERS
FILTERS
with their descriptions.

In the Java Caching API, listeners are mechanisms


ExpiryPolicy Description used to monitor and react to events related to cache
Implementation operations. These events include entry creation,
AccessedExpiryPolicy Expires entries based on update, removal, and eviction. JCache provides two
the time of last access. main types of listeners: Cache Entry Listeners and
When an entry is Cache Manager Listeners. Additionally, JCache
accessed, its expiration supports listener filters, allowing developers to
time is extended by a specify conditions under which listeners should be
fixed duration from the triggered.
last access.
CreatedExpiryPolicy Expires entries based on
CACHE ENTRY LISTENERS
their creation time.
Cache Entry Listeners are invoked when specific
Entries expire after a
events occur on cache entries, such as when an
fixed duration from
entry is created, updated, removed, or evicted.
their creation time.
These listeners can perform actions such as logging,
triggering notifications, or updating external
systems based on the cache events.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


7 JAVA CACHING CHEATSHEET

CACHE MANAGER LISTENERS entries with values greater than 10


return event.getValue() >
Cache Manager Listeners monitor events related to 10;
cache managers, such as when a cache manager is
}
created or closed. They provide hooks for
}
performing initialization or cleanup tasks when
cache managers are instantiated or destroyed.
public class CacheListenerExample {
public static void main(String[]
LISTENER FILTERS
args) {
Listener Filters allow developers to specify // Create a cache
conditions under which listeners should be Cache<String, Integer> cache
triggered. For example, a filter can be used to only = ...; // Get a cache instance
invoke a listener when certain criteria are met,
such as when a cache entry’s value meets a specific // Register the cache entry
condition or when an entry is updated with a listener
particular key.
MyCacheEntryListener
listener = new
import javax.cache.event.*; MyCacheEntryListener();
cache
// Define a cache entry listener .registerCacheEntryListener(new
public class MyCacheEntryListener MutableConfiguration<>().addCacheEnt
implements ryListenerConfiguration(
CacheEntryCreatedListener<String, new
Integer> { CacheEntryListenerConfiguration<>(My
@Override CacheEntryListener.class, new
public void onCreated(Iterable MyCacheListenerFilter(), true,
<CacheEntryEvent<? extends String, ? true)));
extends Integer>> events) {
for (CacheEntryEvent<? // Perform cache operations
extends String, ? extends Integer> cache.put("key1", 15);
event : events) { cache.put("key2", 5);
System.out.println }
("Cache entry created: Key=" + }
event.getKey() + ", Value=" + event
.getValue()); In this example:
}
} • MyCacheEntryListener class implements the
} CacheEntryCreatedListener interface to listen for
cache entry creation events.

// Define a cache listener filter • MyCacheListenerFilter class implements the


public class MyCacheListenerFilter CacheEntryEventFilter interface to filter events
implements CacheEntryEventFilter based on the value of the cache entry.
<String, Integer> { • CacheListenerExample class demonstrates how to
@Override register a cache entry listener with a filter and
public boolean evaluate perform cache operations that trigger the
(CacheEntryEvent<? extends String, ? listener.
extends Integer> event) {
// Only trigger listener for Below is a table listing some of the most popular
listener interface classes in the Java Caching API,

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


8 JAVA CACHING CHEATSHEET

along with their override method and the event remote services, to ensure that requested data is
type they handle. available in the cache for subsequent accesses.
Cache readers are typically used in conjunction
Listener Override Event Type with read-through caching strategies, where cache is
Interface Method treated as the main data store and missing cache
entries are immediately fetched from the integrated
CacheEntryCreat onCreated Cache entry
edListener<K, backend store.
creation
V>
CacheEntryUpdat onUpdated Cache Loader Override Description
Cache entry
edListener<K, Implementatio Method
update
V> n
CacheEntryRemov onRemoved Cache entry javax.cache.Cac load Loads data for
edListener<K, removal heLoader<K, V> the specified
V>
key into the
CacheEntryExpir onExpired Cache entry cache from an
edListener<K, expiration
V> external source.

CacheEntryEvict onEvicted loadAll Loads multiple


Cache entry
edListener<K, eviction key-value pairs
V> into the cache
CacheEntryReadL onRead Cache entry from an
istener<K, V> read (access) external source.

CacheEntryWrite onWrite Cache entry


Listener<K, V> write (put or CACHE WRITERS
replace)
Cache writers, on the other hand, are responsible
CacheEntryListe onCreated, Multiple event for propagating changes made to cached data back
ner<K, V> onUpdated, types to external data sources. They update persistent
onRemoved, storage with changes made to cached data, ensuring
onExpired, consistency between the cache and the underlying
onEvicted
data source. Cache writers are typically used in
CacheManagerLis onManagerCreate Cache manager conjunction with write-through caching strategies,
tener d, creation/destru where data modifications are immediately reflected
onManagerDestro ction
in both the cache and the external data store.
yed

Cache Writer Override Description


LOADERSAND
LOADERS ANDWRITERS
WRITERS
Implementatio Method
n
Cache loaders and cache writers are components
javax.cache.Cac write Writes data for
responsible for interacting with external data
heWriter<K, V> the specified
sources when cache misses or updates occur. They
allow developers to integrate caching with key-value pair
underlying data storage systems, enabling seamless from the cache
synchronization between cached data and to an external
persistent data sources. data source.
delete Deletes data for
CACHE LOADERS the specified
key from the
Cache loaders are responsible for loading data from external data
external sources into the cache when requested source.
data is not found in the cache (cache misses). They
provide a mechanism for populating the cache with
data from persistent storage, such as databases or

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


9 JAVA CACHING CHEATSHEET

Cache Writer Override Description Method Description


Implementatio Method processAll Executes custom logic
n
on multiple cache
writeAll Writes multiple entries atomically,
key-value pairs ensuring that each
from the cache cache entry is locked
to an external during processing.
data source.
deleteAll Deletes ANNOTATIONS
ANNOTATIONS
multiple keys
and their The javax.cache.annotation package offers
associated annotations that developers can use to mark
values from the methods for caching purposes. These annotations
external data provide a convenient way to control caching
source. behavior, such as specifying cache names, cache
entry keys, and caching strategies, without
CACHEENTRY
ENTRYPROCESSORS
PROCESSORS requiring explicit caching logic within the method
CACHE implementation.

A cache entry processor, represented by the


Below is a table with the most commonly used
javax.cache.EntryProcessor interface, is a
JCache annotations and their descriptions.
mechanism for performing atomic operations on
cache entries. It allows developers to execute
Annotation Description
custom logic directly within the cache node (JVM),
providing a way to manipulate cache entries @CacheResult Marks a method whose
without the need for external data sources, return value should be
serialization/de-serialization of data between cached. Specifies the
clients and the cache node, or complex cache name and key,
synchronization mechanisms. and optionally, cache
resolver. Applicable also
Cache entry processors are typically used in on a class for effect on
scenarios where multiple cache operations need to all methods of that class.
be performed atomically, ensuring consistency and
@CachePut Marks a method whose
avoiding race conditions. They are also particularly
return value should be
useful when the cache is distributed (which is quite
cached or updated in the
often the case) over multiple nodes. They offer a
cache. Specifies the
way to encapsulate and execute custom logic on
cache name and key.
cache entries within a single atomic operation,
Applicable also on a
improving performance and reducing the risk of
class for effect on all
data inconsistency.
methods of that class.

javax.cache.EntryProcessor basic methods are @CacheKey Explicitly specify a


presented below. method parameter as
the cache key.
Method Description @CacheValue Explicitly specify a
process Executes custom logic method parameter as
on a cache entry the cache value when
atomically, ensuring that using @CachePut
the cache entry is locked
during processing.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


10 JAVA CACHING CHEATSHEET

Annotation Description String data) {


// This method will update
@CacheRemove Marks a method that
the cache with new data
removes an entry from
// No return value is cached
the cache. Specifies the
cache name and key.
// Simulate data update or
Applicable also on a addition
class for effect on all System.out.println("Updating
methods of that class. cache for key: " + key + ", with
@CacheRemoveAll data: " + data);
Marks a method that
removes all entries from
}
the cache. Specifies the
cache name. Applicable // Remove specific entry from
also on a class for effect cache
on all methods of that @CacheRemove(cacheName =
class. "exampleCache")
@CacheDefaults Specifies default caching public void removeFromCache
settings for methods (@CacheKey String key) {
within a class. Can // This method will remove
define default cache the specified key from the cache
name, key generator, System.out.println("Removing
etc. Applicable on entry from cache for key: " + key);
classes only. }

And here is an example use case of the


// Remove all entries from cache
aforementioned annotations.
@CacheRemoveAll(cacheName =
"exampleCache")
import javax.cache.annotation.*; public void removeAllFromCache()
{
public class ExampleService { // This method will remove
all entries from the cache
// Define a cache named System.out.println("Removing
"exampleCache" all entries from cache");
@CacheResult(cacheName = }
"exampleCache") }
public String getCachedData
(@CacheKey String key) {
MONITORINGAND
MONITORING ANDMANAGEMENT
MANAGEMENT
// This method will be
cached with the key provided
Java Caching API provides management and
// Simulate data retrieval monitoring options during runtime to facilitate the
from an external source observation and control of caching behavior. These
return "Data for key: " + options enable developers to monitor cache usage,
key; performance metrics, and configuration details, as
} well as to manage cache lifecycle and operations
dynamically.
// Update cache or add new entry
@CachePut(cacheName = MANAGEMENT AND MONITORING
"exampleCache") OPTIONS
public void updateCache
• JMX (Java Management Extensions): JCache
(@CacheKey String key, @CacheValue

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


11 JAVA CACHING CHEATSHEET

supports integration with JMX, allowing JMX API Description


caching implementations to expose cache
javax.cache.management. Retrieves a collection of
management and monitoring functionalities as
CacheMXBean.getCacheMXB cache MXBeans
managed beans. Through JMX, developers can eans()
associated with the
access cache-related attributes and operations
cache manager.
programmatically or through management
tools such as JConsole or VisualVM.
These JMX APIs provide standardized interfaces for
• Metrics and Statistics: JCache accessing cache and cache manager management
implementations often provide built-in support and monitoring functionalities. By integrating with
for collecting and exposing cache usage metrics JMX, JCache implementations offer a consistent and
and statistics. These metrics may include interoperable approach to managing and
hit/miss ratios, cache size, eviction counts, and monitoring caching operations during runtime.
latency measurements, providing insights into
cache performance and effectiveness.
VENDORSPECIFIC
VENDOR SPECIFICFEATURES
FEATURES

JMX API FOR JCACHE MANAGEMENT The unwrap method allows developers to obtain the
underlying implementation-specific object
Here’s a table listing some of the most commonly
associated with a specific JCache class or interface.
used JMX APIs for managing and monitoring JCache
This method is useful when developers need to
implementations:
access implementation-specific features or
functionalities that are not provided by the
JMX API Description standard JCache API.
javax.cache.management. Exposes cache
CacheMXBean management and Classes and Interfaces Supporting unwrap:
monitoring
functionalities such as Class/Interface Description
cache statistics, javax.cache.Cache Represents a cache in
configuration details, the JCache API. Allows
and operations through for storing, retrieving,
JMX. and managing cached
javax.cache.management. Provides access to cache key-value pairs.
CacheStatisticsMXBean statistics such as javax.cache.CacheManage Represents a cache
hit/miss counts, eviction r manager in the JCache
counts, and cache size API. Manages the
through JMX. lifecycle of caches and
javax.cache.management. Represents a cache provides cache creation.
CacheManagerMXBean manager’s management javax.cache.Cache.Entry Represents an entry in a
interface, exposing cache. Provides access to
methods for cache the key, value, and
creation, destruction, metadata associated
and management via with the entry.
JMX.
javax.cache.management. Offers cache manager
CacheManagerStatisticsM statistics such as the // Unwrap Cache to Hazelcast ICache
XBean
number of caches ICache<String, String>
created, destroyed, and hazelcastCache = cache.unwrap(
remaining through JMX. ICache.class);

// Unwrap CacheManager to Hazelcast


ICacheManager

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


12 JAVA CACHING CHEATSHEET

ICacheManager hazelcastCacheManager hashing algorithm. Each node is responsible for


= cacheManager.unwrap(ICacheManager storing and managing a subset of the data. This
allows for horizontal scalability as the dataset
.class);
can grow beyond the capacity of a single node.
However, managing data consistency and
// Unwrap Cache.Entry to Hazelcast
cache coherence across partitions can be
ICache.Entry challenging.
com.hazelcast.cache.Cache.Entry<Stri
ng, String> hazelcastCacheEntry = Similar to cache topologies, a cache mode refers to
cacheEntry.unwrap(com.hazelcast.cach wether the cache is part of the client application or
e.Cache.Entry.class); running as a separate service. The following modes
are common across caches in general:

Keep in mind that using this feature is not • Client-side Cache (Embedded mode): In this
recommended if true caching provider portability mode, caching is performed at the client-side,
is what you need, since your application would be typically within the application’s JVM. Cached
coupled to vendor-specific APIs. data is stored locally, reducing the need to fetch
data from remote caches or servers. It can
CACHETOPOLOGIES
CACHE TOPOLOGIESAND
ANDMODES
MODES improve application performance by reducing
network latency and server load. However, it
In the context of caching systems, a cache topology may lead to data inconsistency if the cache is
refers to the arrangement or structure of caches not synchronized with the server-side data.
within a distributed caching environment. Different
• Server-side Cache (Client-Server mode): In
cache topologies offer various trade-offs in terms of
contrast to client-side caching, server-side
performance, scalability, and consistency. Here are
caching stores cached data within cache
some common cache topologies:
servers or nodes. It offloads caching
responsibilities from the client application and
• Single-node Cache: In this topology, there is
centralizes cache management and
only one cache node, typically running on a
coordination. Server-side caching can provide
single server or instance. It’s the simplest form
better control over caching policies and data
of caching and provides basic caching
consistency but may introduce additional
capabilities. However, it lacks scalability and
network latency for cache retrieval operations.
fault tolerance.

• Multiple Independent Caches: Multiple cache Each cache topology and mode has its advantages
nodes operate independently, with each node and disadvantages, and the choice of
managing its own cache. This topology allows topology/mode combination depends on factors
for better scalability compared to a single-node such as application requirements, scalability needs,
cache as multiple cache instances can handle fault tolerance, and data consistency
requests concurrently. However, it lacks data considerations. Organizations often employ a
consistency across caches. combination of cache topologies and modes to meet
their specific caching requirements effectively.
• Replicated Cache: In a replicated cache
topology, the entire dataset is replicated across
RESOURCES
RESOURCES
all cache nodes. This ensures that each cache
node holds a complete copy of the data. It offers
high availability and fault tolerance since any The following resources offer a wealth of
node failure can be mitigated by other replicas. information on caching systems, from basic
However, it may lead to increased network concepts to advanced topics, making them valuable
traffic and memory consumption due to data references for developers, architects, and system
duplication. administrators working with caching technologies.

• Partitioned Cache: In a partitioned cache • Oracle Java Caching API Documentation:


topology, the dataset is partitioned across
◦ Website: Oracle Documentation
multiple cache nodes based on a consistent

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


13 JAVA CACHING CHEATSHEET

◦ Description: The official documentation


provides comprehensive information about
the Java Caching API (JCache), including
guides, tutorials, and API references.

• Ehcache Documentation:

◦ Website: Ehcache Documentation

◦ Description: Ehcache’s documentation


provides in-depth resources on
configuring, deploying, and managing
Ehcache-based caching solutions, along
with best practices and troubleshooting
guides.

• Apache Ignite Documentation:

◦ Website: Apache Ignite Documentation

◦ Description: Apache Ignite’s


documentation provides detailed guides
and tutorials on using Ignite for distributed
caching, in-memory computing, and data
processing.

• Spring Caching Documentation:

◦ Website: Spring Caching Documentation

◦ Description: Spring Framework’s caching


documentation provides guidance on using
Spring’s caching abstraction and
integrations with various caching
providers, including setup, configuration,
and usage examples.

JCG delivers over 1 million pages each month to more than 700K software
developers, architects and decision makers. JCG offers something for everyone,
including news, tutorials, cheat sheets, research guides, feature articles, source code
and more.
CHEATSHEET FEEDBACK
WELCOME
support@javacodegeeks.com

Copyright © 2014 Exelixis Media P.C. All rights reserved. No part of this publication may be SPONSORSHIP
reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, OPPORTUNITIES
mechanical, photocopying, or otherwise, without prior written permission of the publisher. sales@javacodegeeks.com

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!

You might also like