package com.tb.test;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class CachedTest {
// 第一种方法 用hashmap存 然后加锁get方法
// private HashMap<String, Object> cached = new HashMap<String, Object>();
//
// public synchronized Object get(String user){
// Object value=cached.get(user);
// if( value== null){
//
// value ="sss"; //实际上是从数据库中读取
// cached.put(user, value);
// }
//
// return value;
// }
// 第二种方法是用ConcurrentHashMap
// private ConcurrentHashMap<String, Object> cached= new
// ConcurrentHashMap<String, Object>();
//
// public Object get(String user){
// Object value=cached.get(user);
// if(value == null){
//
// value ="sss"; //实际上是从数据库中读取
// cached.put(user, value);
// }
//
// return value;
//
//
// }
// 第三种 用hashmap 加读写锁
private HashMap<String, Object> cached = new HashMap<String, Object>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public Object get(String user) {
readWriteLock.readLock().lock();
Object value = null;
try {
value = cached.get(user);
if ( value == null) {
readWriteLock.readLock().unlock();
readWriteLock.writeLock().lock();
try {
if(value == null){
value = "aa"; // 实际上从数据库读取
cached.put(user, value);
}
} finally {
readWriteLock.writeLock().unlock();
}
readWriteLock.readLock().lock();
}
} finally {
readWriteLock.readLock().unlock();
}
return value;
}
}
java简单实现缓存的三种方法
最新推荐文章于 2024-08-10 17:54:27 发布