=====Article Directory=====
Strong references, soft references, weak references and phantom references
Strong citation
new
Objects created by using methods are strong references by default. During GC, even if there is not enough memory , the OutOfMemoryError
object will not be reclaimed if it is thrown, nor will it be reclaimed if it dies . See StrongReferenceDemo for details .
public class StrongReferenceDemo {
public static void main(String[] args) {
Object o1=new Object();
Object o2=new Object();
o1=null;
System.gc();
System.out.println(o2);
}
}
Soft reference
Needed Object.Reference.SoftReference
to create the display. If there is enough memory , it will not be reclaimed during GC . If the memory is not enough , it will be recycled . Often used in memory-sensitive applications, such as caches. See SoftReferenceDemo for details .
JVM configuration sheet, deliberately generates large objects and configures small memory, so that its memory is not enough to cause OOM, depending on the recovery of soft references
Condition 1. Create a large object
byte[] bytes = new byte[30 * 1024 * 1024];//一个30M的对象
Condition 2. How to configure small memory
In IDEA菜单栏---Run---Edit Configurations ---VM options
fill in the following parameters
-Xms5m -Xmx5m -XX:+PrintGCDetails
Finally, right-click to run.
Configuration diagram
Code
import java.lang.ref.SoftReference;
public class SoftReferenceDemo {
public static void main(String[] args) {
System.out.println("软引用内存充足的情况");
softRef_Memory_Enough();
System.out.println();
System.out.println("软引用内存不足的情况");
softRef_Memory_NotEnough();
}
/**
* 内存够用的时候就保留,不够用就回收!
*/
private static void softRef_Memory_Enough() {
Object o1 = new Object();
SoftReference<Object> softReference = new SoftReference<>(o1);
System.out.println(o1);
System.out.println(softReference.get());
System.out.println("===========");
o1 = null;
System.gc();
System.out.println(o1);
System.out.println(softReference.get());
}
/**
* JVM配置单,故意产生大对象并配置小的内存,让它内存不够用导致OOM,看软引用的回收情况
* IDEA菜单栏---Run---Edit Configurations ---VM options---填写以下参数
* -Xms5m -Xmx5m -XX:+PrintGCDetails
* 右键run
*/
private static void softRef_Memory_NotEnough() {
Object o1 = new Object();
SoftReference<Object> softReference = new SoftReference<>(o1);
System.out.println(o1);
System.out.println(softReference.get());
System.out.println("===========");
o1 = null;
//System.gc();
try {
byte[] bytes = new byte[30 * 1024 * 1024];//一个30M的对象
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(o1);
System.out.println(softReference.get());
}
}
}
Output
Weak reference
Needed Object.Reference.WeakReference
to create the display. Regardless of whether the memory is enough or not, it is reclaimed during GC , and it can also be used for cache. See WeakReferenceDemo for details
Code
import java.lang.ref.WeakReference;
public class WeakReferenceDemo {
public static void main(String[] args) {
Object o1 = new Object();
WeakReference<Object> weakReference = new WeakReference<>(o1);
System.out.println(o1);
System.out.println(weakReference.get());
System.out.println("==========");
o1 = null;
System.gc();
System.out.println(o1);
System.out.println(weakReference.get());
}
}
WeakHashMap
HashMap
Even if key==null
it is traditional , key-value pairs will not be recycled. But if it is WeakHashMap
, once the memory is insufficient key==null
, the key-value pair will be recycled. See WeakHashMapDemo for details .
package jvm;
import java.util.HashMap;
import java.util.WeakHashMap;
public class WeakHashMapDemo {
public static void main(String[] args) {
myHashMap();
System.out.println("===============");
myWeakHashMap();
}
private static void myHashMap() {
HashMap<Integer, String> map = new HashMap<>();
Integer key = 1;
String value = "HashMap";
map.put(key, value);
System.out.println(map);
key = null;
System.out.println(map);
System.gc();
System.out.println(map + "\t" + map.size());
}
private static void myWeakHashMap() {
WeakHashMap<Integer, String> map = new WeakHashMap<>();
// Integer key = 2;
Integer key = new Integer(2);
String value = "WeakHashMap";
map.put(key, value);
System.out.println(map);
key = null;
System.out.println(map);
System.gc();
System.out.println(map + "\t" + map.size());
}
}
Output
{
1=HashMap}
{
1=HashMap}
{
1=HashMap} 1
===============
{
2=WeakHashMap}
{
2=WeakHashMap}
{
} 0
Phantom reference
Soft applications and weak references can get()
obtain objects through methods, but phantom references cannot. Fictitious quotes are nothing but GC at any time and cannot be used alone. They must be used in conjunction with ReferenceQueue . The only purpose of setting a dummy reference is to receive a notification for subsequent operations when the object is recycled , a bit like Spring
a post notification. See PhantomReferenceDemo for details .
Reference queue
After weak references and phantom references are recycled, they will be placed in the reference queue and poll
can be obtained through methods. For the use of reference queues and weak and phantom references, see ReferenceQueueDemo .
Code
package jvm;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
public class PhantomReferenceDemo {
public static void main(String[] args) throws InterruptedException {
Object o1 = new Object();
ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
PhantomReference phantomReference = new PhantomReference(o1, referenceQueue);
System.out.println(o1);
System.out.println(phantomReference.get());
System.out.println(referenceQueue.poll());
System.out.println("===========");
o1 = null;
System.gc();
Thread.sleep(500);
System.out.println(o1);
System.out.println(phantomReference.get());
System.out.println(referenceQueue.poll());
}
}
Output
java.lang.Object@1b6d3586
null
null
===========
null
null
java.lang.ref.PhantomReference@4554617c
Applicable scenarios of soft and weak references
If there is an application that needs to read a lot of local pictures
- If the image is read from the hard disk every time it is read, the performance will be seriously affected.
- If it is loaded into memory all at once, it may cause memory overflow.
At this time, using soft references can solve this problem. The
design idea is to use a HashMap to save the mapping relationship between the path of the image and the soft reference associated with the corresponding image object. When the memory is insufficient, the
JVM will automatically reclaim the cached image objects occupied. Space, thereby effectively avoiding OOM problems
Map<String, SoftReference<Bitmap>> image Cache= new Hash Map<String, SoftReference<Bitmap>>0)