在JAVA中提供了4個級別的引用:強引用,軟引用,若引用,虛引用。強引用就是程序中通常使用的引用類型,強引用的對象是可觸及的,不會被回收。相對的,軟引用,若引用和虛引用的對象是軟可觸及,弱可觸及,虛可觸及,在必定條件下均可以被回收的java
// 強引用 StringBuffer str = new StringBuffer("abc");
軟引用是比強引用弱一點的引用類型,一個對象只有持有軟引用,那麼當堆空間不足時,就會被回收。因此軟引用不會形成內存溢出。數組
import java.lang.ref.SoftReference; /** * Created by dingshuangkun on 2018/1/26. */ public class Main { public static class User{ private String name; private Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public static void main(String[] args){ User user = new User("dingding",20); SoftReference<User> softReference = new SoftReference<>(user); user = null; System.out.println(softReference.get()); System.gc(); System.out.println("--------GC----------"); System.out.println(softReference.get()); byte[] b =new byte[1024*1024*10]; System.gc(); System.out.println("----------建立byte數組後再次GC----------"); System.out.println(softReference.get()); } }
發現即回收,在系統GC時,只要發現若引用,無論系統堆空間的使用狀況如何,都會將對象進行回收。因爲垃圾收集器的線程一般優先級很低,所以並不必定能很快的發現持有若引用對象,在這種狀況下,若引用對象能夠存在較長的時間。一旦一個弱引用對象被垃圾回收器回收,便會加入到一個註冊引用隊列中。ide
import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; /** * Created by dingshuangkun on 2018/1/26. */ public class Main { public static class User{ private String name; private Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public static void main(String[] args){ User user = new User("dingding",20); WeakReference<User> weakReference = new WeakReference<User>(user); user = null; System.out.println(weakReference.get()); System.gc(); System.out.println("--------GC----------"); System.out.println(weakReference.get()); } }
運行結果this
User{name='dingding', age=20}
--------GC----------
nullspa
Process finished with exit code 0
線程
隨時均可能被回收。下面就不介紹了code