search
HomeJavajavaTutorialTo implement Java local cache, start from these points

Cache, I believe everyone is familiar with it. In the project, cache is definitely essential. There are many caching tools on the market, such as Redis, Guava Cache or EHcache.

To implement Java local cache, start from these points

I think everyone must be very familiar with these tools, so we won’t talk about them today. Let’s talk about how to implement local caching. Referring to the above tools, to achieve a better local cache, Brother Pingtou believes that we should start from the following three aspects.

1. Selection of storage collections

To implement local caching, the storage container must be a data structure in the form of key/value. In Java, it is our commonly used Map gather. There are HashMap, Hashtable, and ConcurrentHashMap in Map for us to choose from. If we do not consider data security issues under high concurrency, we can choose HashMap. If we consider data security issues under high concurrency, we can choose one of Hashtable and ConcurrentHashMap. Collection, but we prefer ConcurrentHashMap because the performance of ConcurrentHashMap is better than Hashtable.

2. Expired cache processing

Because the cache is stored directly in the memory, if we do not handle the expired cache, the memory will be occupied by a large number of invalid caches, which is not what we want Yes, so we need to clean these invalid caches. Expired cache processing can be implemented by referring to the Redis strategy. Redis adopts a regular deletion and lazy elimination strategy.

Periodic deletion strategy

The periodic deletion strategy is to detect expired caches at regular intervals and delete them. The advantage of this strategy is that it ensures that expired caches are deleted. There are also disadvantages. Expired caches may not be deleted in time. This is related to the timing frequency we set. Another disadvantage is that if there is a lot of cached data, each detection will also put a lot of pressure on the cup. .

Lazy elimination strategy

The lazy elimination strategy is to first determine whether the cache has expired when using the cache. If it expires, delete it and return empty. The advantage of this strategy is that it can only determine whether it is expired when searching, which has less impact on CUP. At the same time, this strategy has a fatal shortcoming. When a large number of caches are stored, these caches are not used and have expired, and they will become invalid caches. These invalid caches will occupy a large amount of your memory space, and eventually cause the server memory to overflow. .

We briefly took a look at the two expiration cache processing strategies of Redis. Each strategy has its own advantages and disadvantages. Therefore, during use, we can combine the two strategies, and the combined effect is still very ideal.

3. Cache elimination strategy

Cache elimination should be distinguished from expired cache processing. Cache elimination means when the number of our caches reaches the number of caches we specify. After all, our memory is not infinite. If we need to continue adding caches, we need to eliminate some caches in the existing caches according to a certain strategy to make room for the newly added caches. Let's learn about several commonly used cache elimination strategies.

First in, first out policy

The data that enters the cache first will be cleared first when the cache space is insufficient to free up new space to accept new data. The data. This strategy mainly compares the creation time of cached elements. In some scenarios that require relatively high data effectiveness, this type of strategy can be considered to give priority to ensuring that the latest data is available.

Least used strategy

Regardless of whether it is expired or not, based on the number of times the element has been used, clear elements that have been used less often to free up space. This strategy mainly compares the hitCount (number of hits) of elements. This type of strategy can be selected in scenarios where the validity of high-frequency data is ensured.

Least recently used strategy

Regardless of whether it is expired or not, based on the last used timestamp of the element, clear the element with the furthest used timestamp to free up space. This strategy mainly compares the time when the cache was last used by get. It is more applicable in hot data scenarios, and priority is given to ensuring the validity of hot data.

Random elimination strategy

Randomly eliminate a cache regardless of whether it expires. If there are no requirements for cached data, you can consider using this strategy.

Non-elimination strategy

When the cache reaches the specified value, no cache will be eliminated, but no new caches can be added. No more caches can be added until a cache is eliminated. .

The above are three points that need to be considered to implement local cache. After reading this, we should know how to implement a local cache. Let's implement a local cache together.

Implement local cache

In this Demo, we use ConcurrentHashMap as the storage collection, so that we can ensure the safety of the cache even in high concurrency situations. For expired cache processing, I only used the scheduled deletion strategy here, and did not use the scheduled deletion and lazy elimination strategy. You can try it yourself and use these two strategies for expired cache processing. In terms of cache eviction, I'm going with a least-use strategy here. Okay, now that we know the technical selection, let’s take a look at the code implementation.

Cache object class

public class Cache implements Comparable<Cache>{
    // 键
    private Object key;
    // 缓存值
    private Object value;
    // 最后一次访问时间
    private long accessTime;
    // 创建时间
    private long writeTime;
    // 存活时间
    private long expireTime;
    // 命中次数
    private Integer hitCount;
    ...getter/setter()...

Add cache

/**
 * 添加缓存
 *
 * @param key
 * @param value
 */
public void put(K key, V value,long expire) {
    checkNotNull(key);
    checkNotNull(value);
    // 当缓存存在时,更新缓存
    if (concurrentHashMap.containsKey(key)){
        Cache cache = concurrentHashMap.get(key);
        cache.setHitCount(cache.getHitCount()+1);
        cache.setWriteTime(System.currentTimeMillis());
        cache.setAccessTime(System.currentTimeMillis());
        cache.setExpireTime(expire);
        cache.setValue(value);
        return;
    }
    // 已经达到最大缓存
    if (isFull()) {
        Object kickedKey = getKickedKey();
        if (kickedKey !=null){
            // 移除最少使用的缓存
            concurrentHashMap.remove(kickedKey);
        }else {
            return;
        }
    }
    Cache cache = new Cache();
    cache.setKey(key);
    cache.setValue(value);
    cache.setWriteTime(System.currentTimeMillis());
    cache.setAccessTime(System.currentTimeMillis());
    cache.setHitCount(1);
    cache.setExpireTime(expire);
    concurrentHashMap.put(key, cache);
}

Get cache

/**
 * 获取缓存
 *
 * @param key
 * @return
 */
public Object get(K key) {
    checkNotNull(key);
    if (concurrentHashMap.isEmpty()) return null;
    if (!concurrentHashMap.containsKey(key)) return null;
    Cache cache = concurrentHashMap.get(key);
    if (cache == null) return null;
    cache.setHitCount(cache.getHitCount()+1);
    cache.setAccessTime(System.currentTimeMillis());
    return cache.getValue();
}

Get the least used cache

/**
     * 获取最少使用的缓存
     * @return
     */
    private Object getKickedKey() {
        Cache min = Collections.min(concurrentHashMap.values());
        return min.getKey();
    }

Expired cache detection method

/**
 * 处理过期缓存
 */
class TimeoutTimerThread implements Runnable {
    public void run() {
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(60);
                expireCache();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建多久后,缓存失效
     *
     * @throws Exception
     */
    private void expireCache() throws Exception {
        System.out.println("检测缓存是否过期缓存");
        for (Object key : concurrentHashMap.keySet()) {
            Cache cache = concurrentHashMap.get(key);
            long timoutTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime()
                    - cache.getWriteTime());
            if (cache.getExpireTime() > timoutTime) {
                continue;
            }
            System.out.println(" 清除过期缓存 : " + key);
            //清除过期缓存
            concurrentHashMap.remove(key);
        }
    }
}

The above is the detailed content of To implement Java local cache, start from these points. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools