import java.util.concurrent.ConcurrentHashMap;
public class LocalCacheExample {
// 使用 ConcurrentHashMap 实现简单的本地缓存
private static final ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<>();
public static void main(String[] args) {
// 模拟缓存操作
String key = "exampleKey";
String value = "exampleValue";
// 添加数据到缓存
putInCache(key, value);
// 从缓存中获取数据
Object cachedValue = getFromCache(key);
System.out.println("Cached Value: " + cachedValue);
// 移除缓存中的数据
removeFromCache(key);
}
// 将数据放入缓存
public static void putInCache(String key, Object value) {
cache.put(key, value);
System.out.println("Put into cache: " + key + " -> " + value);
}
// 从缓存中获取数据
public static Object getFromCache(String key) {
return cache.get(key);
}
// 从缓存中移除数据
public static void removeFromCache(String key) {
cache.remove(key);
System.out.println("Removed from cache: " + key);
}
}
ConcurrentHashMap
来实现一个线程安全的本地缓存。ConcurrentHashMap
是 Java 中的一个高效并发哈希表,适用于多线程环境。以上代码展示了如何使用 ConcurrentHashMap
实现一个简单的本地缓存,并提供了基本的增删查功能。
上一篇:java int 转long
下一篇:java创建文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站