It’s a very very important interview question.
What are 4 different types of references in java >
- Strong reference
- Weak Reference
- Soft Reference
- Phantom Reference
I will try to explain you this topic in very simple and crystal clear language which will be very for you to understand.
1) Strong reference
Its use almost everywhere in java.
Example >
String str= "a"; //It’s strong reference.
String won’t get garbage collected until and unless str is explicitly set to null or its used nowhere in program.
2) Weak Reference
import java.lang.ref.WeakReference;
public class ExampleClass {
public static void main(String[] args) {
String str="a";
WeakReference<String> wr = new WeakReference<String>(str); //WeakReference to str
}
}
|
Now, whenever we set
str=null;
Immediately WeakReference’s object wr becomes eligible for garbage collection and is garbage collected.
3) Soft Reference
import java.lang.ref.SoftReference;
public class ExampleClass {
public static void main(String[] args) {
String str="a";
SoftReference<String> sr = new SoftReference<String>(str); //SoftReference to str
}
}
|
Now, whenr we set
str=null;
SoftReference’s object sr becomes eligible for garbage collection and is garbage collected whenever memory is required.
When to use SoftReference in java?
Whenever there is crunch of memory in application. It can used in caching as well, where we might remove some objects.
4) Phantom Reference
import java.lang.ref.PhantomReference;
public class ExampleClass {
public static void main(String[] args) {
String str="a";
PhantomReference<String> pr = new PhantomReference<String>(str); //PhantomReference to str
}
}
|
Now, when we set
str=null;
Immediately PhantomReference’s object pr becomes eligible for garbage collection but depends on garbage collector when it will get collected.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
Related >
Constructor in java - Constructor chaining, access modifiers with constructors, constructor overloading, exception thrown, constructors are not inherited
Singleton in java, Doubly Locked Singleton class/ Lazy initialization, enum singleton, eager initialization in static block
Interface in java - Multiple inheritance, Marker interfaces, When to use interface practically, 12 features
Abstract class and abstract methods in java - When to use abstract class or interface practically, 10 features
Labels:
Core Java