TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|

实例一:
下面程序通过SoftReference数组保存100个Person对象,当系统内存充足时,SoftReference引用和强引用没有太大的区别。
- import java.lang.ref.*;
- class Person
- {
- String name;
- int age;
- public Person(String name , int age)
- {
- this.name = name;
- this.age = age;
- }
- public String toString()
- {
- return "Person[name=" + name
- + ", age=" + age + "]";
- }
- }
- public class SoftReferenceTest
- {
- public static void main(String[] args) throws Exception
- {
- SoftReference
-
- [] people =
- new SoftReference[100];
- for (int i = 0 ; i < people.length ; i++)
- {
- people[i] = new SoftReference
-
- (new Person(
- "名字" + i , (i + 1) * 4 % 100));
- }
- System.out.println(people[2].get());
- System.out.println(people[4].get());
- //通知系统进行垃圾回收
- System.gc();
- System.runFinalization();
- //垃圾回收机制运行之后,SoftReference数组里的元素保持不变
- System.out.println(people[2].get());
- System.out.println(people[4].get());
- }
- }
-
-
复制代码 运行:
C:java>java SoftReferenceTest
Person[name=名字2, age=12]
Person[name=名字4, age=20]
Person[name=名字2, age=12]
Person[name=名字4, age=20]
实例二: 将上面程序数组的长度改为100000,并使用下面命令运行:
C:java>java -Xmx2m -Xms2m SoftReferenceTest
null
null
null
null
软引用所引用的对象被垃圾回收。
实例三:
将上面程序的软引用改为强引用,无任系统内存如何紧张,JVM垃圾回收机制都不会回收强引用所引用的JAVA对象。- import java.lang.ref.*;
- public class StrongReferenceTest
- {
- public static void main(String[] args)
- throws Exception
- {
- Person[] people =
- new Person[100000];
- for (int i = 0 ; i < people.length ; i++)
- {
- people[i] = new Person(
- "名字" + i , (i + 1) * 4 % 100);
- }
- System.out.println(people[2]);
- System.out.println(people[4]);
- //通知系统进行垃圾回收
- System.gc();
- System.runFinalization();
- //StrongReference数组里不受任何影响
- System.out.println(people[2]);
- System.out.println(people[4]);
- }
- }
复制代码 运行:
C:java>java -Xmx2m -Xms2m StrongReferenceTest
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.lang.StringBuilder.toString(StringBuilder.java:405)
at StrongReferenceTest.main(StrongReferenceTest.java:23) |
|