After reading the books, surfing the nets regarding the type of references in Java, I still have some doubts (or I may have interpreted the concept wrong).
It would be a great help for me if anyone clear my doubts.
Let me take an example of a class containing class variables, instance variables and local variables.
public class Test {
public static ArrayList<String> listCommon = new ArrayList<String>();
private HashMap<String, String> mapInstance;
public Test() {
mapInstance = new HashMap<String, String>();
}
public void doSomething(String key) {
ArrayList<String> local = new ArrayList<String>();
if(key != null){
local.add(mapInstance.get(key));
}
System.out.println("Value is added in instance Map: ", mapInstance.get(key));
}
}
My Question are;
1. are listCommon
(static variable) and mapInstance
(instance variable) Strong reference towards Garbage Collector?
2. Is variable local
(defined and used in method) a Weak reference?
3. How the Phantom reference and Soft reference came in picture?
4. OR above 3 concepts are invalid; means that Java defines the references only if you explicitly used the type defined in java.lang.ref package?
Any help would be great for me.
- are listCommon (static variable) and mapInstance (instance variable) Strong reference towards Garbage Collector?
They are strong references, yes.
- Is variable local (defined and used in method) a Weak reference?
No, it is a local variable, so it is a variable, so it is still a strong reference.
- How the Phantom reference and Soft reference came in picture?
If you use them. If you don't use them you don't need to worry about them. They are for writing various kinds of caches really.
- OR above 3 concepts are invalid; means that Java defines the references only if you explicitly used the type defined in java.lang.ref package?
Reference variables are always strong. The other kinds only arise when you use them explicitly.
Answer to questions:
Yes, they are strong reference. Weak Reference are defined using Weak reference Object.
No, reason as 1).
Phantom Reference doesn't apply in your example. By default, all instances are strong reference.
Yes, you specify weak/phantom reference using the java.lang.ref
package. By default, strong reference is used.
Note: A wikipedia explaination of Weak Reference might be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With