Java的简单理解(19)---引用(强弱软虚)

Java
引用分类
  • 强引用-StrongReference:引用指向对象,gc(Garbage Collection)运行时不回收。
  • 软引用-SoftReference:运行时可能回收(jvm内存不够)。常做缓存。
  • 弱引用-WeakReferencegc运行时立即回收。
  • 虚引用-PhantomReference:类似于无引用,主要跟踪对象被回收的状态,不能单独使用,必须与引用队列(ReferenceQueue)联合使用。
    public void test1() {
        // 字符串常量池 共享(不能回收)
        String str = "You are very good!";

        // 弱引用管理对象
        WeakReference wr = new WeakReference(str);

        Log.d(TAG,"gc运行前:" + wr.get());

        // 断开引用
        str = null;

        // 通知回收
        System.gc();

        // 开始回收
        System.runFinalization();

        Log.d(TAG,"gc运行后:" + wr.get());
    }

gc运行前:You are very good!
gc运行后:You are very good!
public void test2() {
        
    String str = new String("You are very good!");

    // 弱引用管理对象
    WeakReference wr = new WeakReference(str);

    Log.d(TAG,"gc运行前:" + wr.get());

    // 断开引用
    str = null;

    // 通知回收
    System.gc();

    // 开始回收
    System.runFinalization();

    Log.d(TAG,"gc运行后:" + wr.get());
}
gc运行前:You are very good!
gc运行后:null
1. WeakHashMap 键为弱引用,回收键后自动删除key-value对象
public void test3() {

    WeakHashMap map = new WeakHashMap<>();

    // 测试数据
    // 常量池对象,不会回收
    map.put("a","a");
    map.put("b","b");

    // gc运行 已被回收
    map.put(new String("c"),"c");
    map.put(new String("d"),"d");

    System.gc();
    System.runFinalization();

    int a  = map.size();

}

map.size() = 3,包含 a b d
没有c
2. IdentityHashMap
  • 键只以地址去重,而不是比较hashcode和equals
  • 注意:键是常量池中的字符串
public void test4() {

    IdentityHashMap map = new IdentityHashMap<>();

    map.put("a","a");
    map.put("a","a");

    int a = map.size();

    map.put(new String("c"),"c");
    map.put(new String("d"),"d");

    int b = map.size();
}

a = 1;
b = 3;
3. EnumMap
  • 键必须为枚举的值
  • 构造器:public EnumMap(指定枚举class对象)
public void test5() {

    EnumMap map = new EnumMap(Season.class);

    map.put(Season.SPRING,"春困");
    map.put(Season.SUMMER,"夏无力");
    map.put(Season.AUTUMN,"秋乏");
    map.put(Season.WINTER,"冬眠");

    int a = map.size();
}

a = 4

enum Season {
    SPRING,SUMMER,AUTUMN,WINTER
}

你可能感兴趣的:(Java的简单理解(19)---引用(强弱软虚))