利用软引用实现缓存机制


首先,我们需要对java对象的4种引用有一个大概的认识。

java对象的引用包括强引用软引用弱引用虚引用

顾名思义,他们表示对象的引用强度依次递减

他们有什么作用?
最重要的目的就是方便gc进行回收。我们都知道,java的一大特点就是开发者不用关心内存的使用,jvm会帮助我们自动回收无用的内存空间(对象),而哪些对象需要回收就是通过引用来作为一种判断依据。

一、四种引用

1.强引用

通常我们使用new关键字分配的对象都是强引用。例如:

1
Object obj = new Object();

强引用的对象永远不会被回收。如果想要回收Object对象的话,将obj的引用置为空即可,gc会在合适的时机将它回收。

1
2
Object obj = new Object();
obj = null; //Object准备被回收

2.软引用

软引用有一个非常好的特性:当内存充足时,软引用的对象不会被回收,随时可以调用;当内存不足时,软引用的对象会被回收。

基于这个特性,很多高速缓存、页面缓存、图片缓存都是通过这个原理实现的。

获得一个软引用:

1
2
3
Object obj = new Object();
SoftReference aSoftRef=new SoftReference(obj);
obj = null;

软引用可以通过get()方法获得对象的强引用。

1
Object objNew = aSoftRef.get();

3.弱引用

弱引用就随意多了,是一个佛系青年,哈哈。
不管内存的使用状态如何,什么时候进行内存回收就什么时候被清理掉。

1
WeakReference<Object> reference = new WeakReference<Object>(new Object());

4.虚引用

虚引用是四种引用中最弱的一种,只能和引用队列一起使用,可以用来监控对象是否被回收了。也就是说,你可以通过监控引用队列来让一个对象被回收之前做点什么。

1
2
ReferenceQueue<String> queue = new ReferenceQueue<String>();  
PhantomReference<String> pr = new PhantomReference<String>(new String("Hello World!"), queue);

二、利用软引用实现数据缓存

首先,我们需要一个model类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Car {

private double price;
private String colour;
private String name;
private String id;

public Car(double price, String colour) {
this.price = price;
this.colour = colour;
getDabaseData(); //假装去了数据库 - -
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

public String getColour() {
return colour;
}

public void setColour(String colour) {
this.colour = colour;
}

public void getDabaseData(){
//一系列复杂操作,因为很复杂所以要做缓存,^_^
this.name = "数据库加载到名字";
this.id = "11111111111111";
}

@Override
public String toString() {
return "Car{" +
"price=" + price +
", colour='" + colour + '\'' +
", name='" + name + '\'' +
", id='" + id + '\'' +
'}';
}
}

下来是重头戏,缓存器的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class CarCache {
//缓存器
private static CarCache cache;
//缓存队列
private HashMap<String,CarSoftCache> SoftRefs;
//引用队列
private ReferenceQueue<Car> queue;

private class CarSoftCache extends SoftReference<Car>{

String _key = null;

public CarSoftCache(Car car,ReferenceQueue<Car> queue) {
super(car,queue);
_key = car.getColour();

}
}
//缓存肯定得单例啦
private CarCache(){
SoftRefs = new HashMap<String,CarSoftCache>();
queue = new ReferenceQueue<Car>();
}

public static CarCache getInstance(){
if(cache==null){
cache = new CarCache();
}
return cache;
}

//将对象加入缓存队列
private void cacheCar(Car car){
cleanCache();
CarSoftCache carSoftCache = new CarSoftCache(car,queue);
SoftRefs.put(car.getColour(),carSoftCache);
}


//主要方法:获取car的内容
public Car getCarByCache(String colour){
Car car = null;
if(SoftRefs.containsKey(colour)){
car = SoftRefs.get(colour).get();
System.out.println("找到缓存,读取car");

}
if(car==null){
//没找到,进行复杂操作
car = new Car(60000,colour);
System.out.println("无缓存,重新生成Car!");
this.cacheCar(car);
}
return car;
}



//清除指向car对象已经被清除的软引用
private void cleanCache(){
CarSoftCache carSoftCache;
while((carSoftCache = (CarSoftCache)queue.poll())!=null){
SoftRefs.remove(carSoftCache._key);
}
}

//清除全部缓存
public void clearCache(){
cleanCache();
SoftRefs.clear();
System.gc();
System.runFinalization();
}
}

下面是测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class test {

public static void main(String[] args) {
Car car = CarCache.getInstance().getCarByCache("white");
System.out.println("打印信息:"+car);
Car car2 = CarCache.getInstance().getCarByCache("white");
System.out.println("打印信息:"+car2);
Car car3 = CarCache.getInstance().getCarByCache("black");
System.out.println("打印信息:"+car3);
Car car4 = CarCache.getInstance().getCarByCache("white");
System.out.println("打印信息:"+car4);

}
}

代码没有很复杂的地方,总体的思路就是获取对象时检查缓存队列,没有就存进去,有的话就拿出来。

下面是运行结果:
结果

-------------本文结束,感谢您的阅读-------------

本文标题:利用软引用实现缓存机制

文章作者:饭饭君~

发布时间:2018年12月03日 - 14:11

最后更新:2019年04月23日 - 10:52

原始链接:https://yangcf.github.io/2018/12/03/利用软引用实现缓存机制/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

如果我的文章有帮助到你,欢迎打赏~~
0%