Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java to implement a simple memory cache

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use Java to achieve a simple memory cache", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Java to implement a simple memory cache.

1. Scene

In Java applications, for data with high access frequency and few updates, the usual solution is to add this kind of data to the cache. Read caching is much more efficient than reading from the database.

In the cluster environment, the commonly used distributed caches are Redis, Memcached and so on. However, in some business scenarios, it may not be necessary to build a complex distributed cache system. In a stand-alone environment, you usually want to use internal caching (LocalCache).

two。 Scheme

Self-developed based on JSR107 specification.

Data cache is realized based on ConcurrentHashMap.

3. JSR107 specification

Documentation: https://jcp.org/en/jsr/detail?id=107 (just learn about it, it's not a big application)

target

Provides applications with the ability to cache Java objects.

A set of general caching concepts and tools are defined.

Minimize the cost of learning for developers to use caching.

Maximize the portability of applications between different cache implementations.

Supports in-process and distributed caching implementations.

Core concept

Java Caching defines five core interfaces, namely CachingProvider, CacheManager, Cache, Entry and Expiry.

CachingProvider defines the creation, configuration, acquisition, management, and control of multiple CacheManager. An application can access multiple CachingProvider while it is running.

CacheManager defines the creation, configuration, acquisition, management, and control of multiple uniquely named Cache that exist in the context of the CacheManager. A CacheManager is owned by only one CachingProvider.

Cache is a Map-like data structure and temporarily stores values indexed by key. A Cache is owned by only one CacheManager.

Entry is a key-value pair stored in Cache.

Each entry stored in Cache has a defined validity period, that is, Expiry Duration. Once this time has elapsed, the entry is out of date. Once expired, entries are inaccessible, updated, and deleted. The cache validity period can be set through ExpiryPolicy.

4. Use Map to implement a simple cache package com.study.cache.java;import java.lang.ref.SoftReference;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;/** * use Map to achieve a simple cache function * @ author Huaxia Purple Dome * / public class MapCacheDemo {/ / use ConcurrentHashMap, thread safety requirements. / / use SoftReference as the mapping value, because the soft reference ensures that the referenced object will be deleted if memory is missing before throwing the OutOfMemory. / / in the constructor, I created a daemon thread that scans every 5 seconds and cleans up expired objects. Private static final int CLEAN_UP_PERIOD_IN_SEC = 5; private final ConcurrentHashMap cache = new ConcurrentHashMap (); public MapCacheDemo () {Thread cleanerThread = new Thread (()-> {while (! Thread.currentThread () .isInterrupted () {try {Thread.sleep (CLEAN_UP_PERIOD_IN_SEC * 1000); cache.entrySet () .removeIf (entry-> Optional.ofNullable (entry.getValue ()) .map (SoftReference::get) .map (CacheObject::isExpired) .orElse (false)) } catch (InterruptedException e) {e.printStackTrace ();}); cleanerThread.setDaemon (true); cleanerThread.start ();} public void add (String key, Object value, long periodInMillis) {if (key = = null) {return;} if (value = = null) {cache.remove (key) } long expireTime = System.currentTimeMillis () + periodInMillis; cache.put (key, new SoftReference (new CacheObject (value, expireTime));} public void remove (String key) {cache.remove (key);} public Object get (String key) {return Optional.ofNullable (cache.get (key)) .map (SoftReference::get) .filter (cacheObject->! CacheObject.isExpired () .map (CacheObject::getValue) .orElse (null);} public void clear () {cache.clear ();} public long size () {return cache.entrySet () .stream () .filter (entry-> Optional.ofNullable (entry.getValue ()) .map (SoftReference::get) .map (cacheObject->! CacheObject.isExpired () .orElse (false) .count ();} / cached object value private static class CacheObject {private Object value; private long expiryTime; private CacheObject (Object value, long expiryTime) {this.value = value; this.expiryTime = expiryTime;} boolean isExpired () {return System.currentTimeMillis () > expiryTime } public Object getValue () {return value;} public void setValue (Object value) {this.value = value;}} package com.study.cache.java;/** * MapCache Test Class * @ author Chinese Purple Dome * / public class MapCacheDemoTests {public static void main (String [] args) throws InterruptedException {MapCacheDemo mapCacheDemo = new MapCacheDemo () MapCacheDemo.add ("uid_10001", "{1}", 5 * 1000); mapCacheDemo.add ("uid_10002", "{2}", 5 * 1000); mapCacheDemo.add ("uid_10003", "{3}", 5 * 1000); System.out.println ("fetch value from cache:" + mapCacheDemo.get ("uid_10001")); Thread.sleep (5000L) System.out.println ("after 5 seconds"); System.out.println ("take the value from the cache:" + mapCacheDemo.get ("uid_10001")); / / 5 seconds later the data is automatically cleared}}. I believe you have a deeper understanding of "how to use Java to achieve a simple memory cache". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report