利用HashMap实现下java的缓存机制
java缓存也就是将数据存放于方便取出的地方。 这里用hashMap 模拟下, 说下其他的, List和Map的数据检索速度问题,不知道大家有没有研究过,可能面试中会问到。
直接上例子

package cache;
import java.util.*;
/**
* cache的模拟
* 定义一个map 对象
* @author ninihao
*
*/
public class MyCache {
/**
* 创建一个map模拟下
*/
private Map<String, Object> cacheMap = new HashMap<String, Object>();
public Object getValue(String key)
{
Object obj = cacheMap.get(key);
/**
* 判断下 如果是空的话获取值 存放于map中
*/
if(obj == null)
{
obj = new SingletonUtils().getIntance().getValues("name");
cacheMap.put("name", obj);
}
return obj;
}
}
这边是一个MyCache类, 就是将properties文件中的name属性值的读取, 关于properties的解析工具类运用单例模式package cache;
import java.io.InputStream;
import java.util.Properties;
/**
* 单例模式解析配置文件
*
* @author YanD
*
*/
public class SingletonUtils {
private static SingletonUtils singletonUtils;
private static Properties prop;
public SingletonUtils() {
try {
prop = new Properties();
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("cache/YanD.properties");
prop.load(in);// 这边会抛异常 捕捉下
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static SingletonUtils getIntance() {
if (singletonUtils == null) {
singletonUtils = new SingletonUtils();
}
return singletonUtils;
}
public String getValues(String key) {
return prop.getProperty(key);
}
}
YanD.propertiesname = YanD
测试类package cache;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
MyCache myCache = new MyCache();
System.out.println(System.currentTimeMillis());
String name = (String)myCache.getValue("name");
System.out.println(System.currentTimeMillis() + ":"+name);
String name2 = (String)myCache.getValue("name");
System.out.println(System.currentTimeMillis() +":"+name2);
}
}
运行程序输出结果
1465129991008
1465129991016:YanD
1465129991017:YanD
1465129991016:YanD
1465129991017:YanD
从毫秒数看快了很多,
真正的开发中的缓存实现比这个复杂太多, 也有许多成熟的框架以及第三方工具供我们使用例如Ehcache,本篇只是运用缓存的思想写个小例子,算是抛砖引玉吧

ps : 个人微信号,欢迎喜欢技术的一起交流 (注明 csd上看到的就可以)