SoFunction
Updated on 2025-04-14

Summary of 4 implementation methods of local cache in Java

Preface

In Java development, caching technology is one of the key means to improve application performance.

Today, let’s talk about four mainstream local caching technologies in Java, and use instance code to help everyone better understand and apply these technologies.

1. Basic cache implementation

First of all, let’s start with the most basic cache implementation.

A simple caching system usually includes the functions of caching entity classes, adding, deleting, querying and clearing caches.

1. Cache Entity Class

The cache entity class is used to store cached key-value pairs and expiration time.

The code is as follows:.

public class CacheEntity {
    private String cacheKey;
    private Object cacheValue;
    private long expireTime; // Expired time stamp
    // Constructor, getter and setter omitted}

2. Cache tool class

Next, we implement a cache tool class, usingConcurrentHashMapAs a storage structure, and expiration data is cleared through timing tasks.

import .*;
import ;

publicclassCacheUtil {
    privatefinalstatic Map<String, CacheEntity> CACHE_MAP = newConcurrentHashMap<>();
    privatestaticScheduledExecutorServiceexecutorService= ();

    static {
        (() -> {
            longcurrentTime= ();
            CACHE_MAP.values().removeIf(entity -> () < currentTime);
        }, 0, 500, );
    }

    publicstaticvoidput(String key, Object value, long expireTimeInSeconds) {
        longexpireTime= () + expireTimeInSeconds * 1000;
        CACHE_MAP.put(key, newCacheEntity(key, value, expireTime));
    }

    publicstatic Object get(String key) {
        CacheEntityentity= CACHE_MAP.get(key);
        if (entity == null || () < ()) {
            CACHE_MAP.remove(key);
            returnnull;
        }
        return ();
    }

    publicstaticvoiddelete(String key) {
        CACHE_MAP.remove(key);
    }

    publicstaticvoidclear() {
        CACHE_MAP.clear();
    }
}

Test code:

public class Test {
    public static void main(String[] args) throws InterruptedException {
        ("name", "zzc", 10L);
        ("First query result:" + ("name"));
        (2000L);
        ("Second Query Results:" + ("name"));
    }
}

2. Guava LoadingCache

Guava is a Java basic library provided by Google, among which LoadingCache is a powerful caching tool.

1. Use examples

import .*;

import ;
import ;

publicclassTest {
    publicstaticvoidmain(String[] args)throws ExecutionException {
        LoadingCache&lt;String, String&gt; cache = ()
                .concurrencyLevel(8)
                .expireAfterWrite(10, )
                .build(newCacheLoader&lt;String, String&gt;() {
                    @Override
                    public String load(String key)throws Exception {
                        return"default_value";
                    }
                });

        ("name", "zzc");
        StringnameValue= ("name");
        StringageValue= ("age", () -&gt; "default_age");
        StringsexValue= ("sex", () -&gt; "key does not exist");

        ("nameValue: " + nameValue);
        ("ageValue: " + ageValue);
        ("sexValue: " + sexValue);
    }
}

In the above code, when calling(key)When the method is used, if there is no corresponding key in the cache, it will passCacheLoaderofloadMethod loads default values.

3. SpringBoot integrates Caffeine

Caffeine is a high-performance Java cache library, and SpringBoot provides seamless integration with Caffeine.

1. Turn on the cache function

Add on startup class@EnableCachingannotation.

import ;
import ;
import ;

@EnableCaching
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        (, args);
    }
}

2. Configure the cache manager

import ;
import ;
import ;
import ;
import ;
import ;

import ;

@Configuration
@EnableCaching
publicclassCacheConfig {

    @Bean("caffeineCacheManager")
    public CacheManager cacheManager() {
        CaffeineCacheManagercacheManager=newCaffeineCacheManager("userCache");
        ("userCache").getConfig().setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine<Object, Object> caffeineCacheBuilder() {
        return ()
                .expireAfterWrite(10, )
                .maximumSize(100);
    }
}

3. Use cache annotations

import ;
import ;
import ;

@Service
publicclassUserService {

    // Simulate database operations    private Map&lt;Integer, User&gt; userMap = newHashMap&lt;&gt;();

    @Cacheable(value = "userCache", key = "#id")
    public User getUserById(Integer id) {
        // Assume that user data is obtained from the database        Useruser=newUser();
        (id);
        ("User" + id);
        (id, user);
        return user;
    }

    @CacheEvict(value = "userCache", key = "#id")
    publicvoiddeleteUserById(Integer id) {
        (id);
    }
}

4. JetCache—Alibaba’s distributed caching framework

JetCache is a distributed caching framework based on Spring and Redis by Alibaba, providing powerful cache abstraction and annotation support.

1. Introduce dependencies

existAdd JetCache dependency to it.

&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;jetcache-starter-redis&lt;/artifactId&gt;
    &lt;version&gt;Latest version number&lt;/version&gt;
&lt;/dependency&gt;

2. Configure JetCache

existConfigure JetCache in.

jetcache:
  stat:enable# Turn on statisticsremote:
    default:
      type:redis
      keyConvertor:fastjson# Serialization method      valueEncoder:java
      valueDecoder:java
      poolConfig:
        minIdle:5
        maxIdle:20
        maxTotal:50
      host:localhost
      port: 6379

3. Use JetCache annotation

import ;
import ;
import ;
import ;
import ;

@Service
publicclassUserService {
    @Cached(name = "userCache", key = "#id", cacheType = )
    public String getUser(int id) {
        return"user:" + id;
    }

    @CacheUpdate(name = "userCache", key = "#id", value = "#user")
    publicvoidupdateUser(int id, String user) {
        ("Update User:" + user);
    }

    @CacheInvalidate(name = "userCache", key = "#id")
    publicvoiddeleteUser(int id) {
        ("Delete user:" + id);
    }
}

JetCache supports a combination of local cache and remote cache, which is very suitable for distributed systems.

Summarize

Today we explored a variety of implementations of Java local caching, from handwriting caching to Guava Cache, Caffeine, Ehcache and JetCache. Each method has its own characteristics and applicable scenarios.

This is the end of this article about the 4 implementation methods of local cache in Java. For more related content on local cache implementation of Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!