Reference types in Java
There are four types reference types in Java
Namely,
StrongReference:
Strong reference is very common in our daily code, for example
Object obj = new Object();
Employee emp = new Employe (EmployeeName, EmployeeAge);
As long as Strong Reference exists, the garbage collector will not recycle the object reference,
And when the memory is no enough, JVM will throw OutOfMemory Error.
To break the Strong Reference tie:
1. Assign the null value for example emp = null;
2. The object is created within a method
在一个方法内部创建的对象,由于强引用保存在栈上,所引用的对象保存在堆空间中,当这个方法运行完成就会退出方法栈,从而让强引用断裂
SoftReference:
If the memory is still enough, the Garbage collector will not re-cycle it, but if the JVM runs out of Memory, it will be recycled by GC.
the out put would be
Employee [id = 1441, name = KK]
Employee [id = 1441, name = KK]
WeakReference:
Employee [id = 1441, name = KK]
Null
no matter if the memory is enough or not , the Reference will be recycled by Garbage collector.
PhantomReference:
To Conclude: