Caching in Java: Redis, Ehcache, Caffeine, Hazelcast — Overview and Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Caching in Java: Redis and Other Solutions



Caching is one of the key techniques for optimizing the performance of Java applications. It reduces response time, lowers the load on databases, and decreases infrastructure costs. In this article, we will take a detailed look at popular libraries and tools for caching in Java: Redis, Ehcache, Caffeine, and Hazelcast. You will learn when and which tool to choose, and see working code examples.



Why is caching needed?

Without a cache, every data request leads to reading from a slow storage (database, external API). A cache stores frequently requested data in fast memory (in-process or in-memory), providing:

  • 10–100x faster access
  • Reduced database load
  • Increased system throughput
  • Resource savings


1. Redis — Distributed Cache

Redis is an in-memory data store that runs as a separate server. It supports complex data structures (strings, lists, sets, hashes) and key expiration mechanisms (TTL). For Java, the Jedis or Lettuce client is used.



Example of using Redis with Jedis

import redis.clients.jedis.Jedis;

public class RedisCacheExample { public static void main(String[] args) { try (Jedis jedis = new Jedis("localhost", 6379)) { // Set a value with a TTL of 60 seconds jedis.setex("user:123", 60, "{\\"name\\":\\"Alice\\",\\"role\\":\\"admin\\"}");

// Read the value String userData = jedis.get("user:123"); System.out.println("Cached data: " + userData);

// Check if key exists System.out.println("Key exists: " + jedis.exists("user:123")); } }}


Pros of Redis:

  • Support for clustering and replication
  • Persistence (RDB, AOF)
  • Rich set of commands (INCR, SORT, PUB/SUB)
  • Excellent integration with Spring Boot via spring-boot-starter-data-redis


Cons:

  • Network latency (separate process)
  • Requires administration
  • Not suitable for caches with very small data volumes (connection overhead)


2. Ehcache — Mature In-Process Cache

Ehcache is one of the oldest caching libraries for Java. It runs inside the JVM, supports disk storage (BigMemory), and is fully compatible with JCache (JSR-107). It is ideal for monolithic applications.



Example of Ehcache configuration via XML

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns="http://www.ehcache.org/v3"        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.10.xsd">    <cache alias="users">        <key-type>java.lang.String</key-type>        <value-type>java.lang.String</value-type>        <heap>1000</heap>        <expiry>            <ttl unit="seconds">300</ttl>        </expiry>    </cache></config>


Example of using Ehcache in code

import org.ehcache.Cache;import org.ehcache.CacheManager;import org.ehcache.config.builders.CacheManagerBuilder;import org.ehcache.xml.XmlConfiguration;

public class EhcacheExample { public static void main(String[] args) { XmlConfiguration xmlConfig = new XmlConfiguration( EhcacheExample.class.getResource("/ehcache.xml")); try (CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig)) { cacheManager.init(); Cache<String, String> users = cacheManager.getCache("u

Recommendations