Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it true that Java implicitly defines references to the objects used in classes?

Tags:

java

reference

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.

like image 384
Naved Avatar asked Oct 25 '11 04:10

Naved


2 Answers

  1. are listCommon (static variable) and mapInstance (instance variable) Strong reference towards Garbage Collector?

They are strong references, yes.

  1. 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.

  1. 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.

  1. 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.

like image 157
user207421 Avatar answered Oct 19 '22 22:10

user207421


Answer to questions:

  1. Yes, they are strong reference. Weak Reference are defined using Weak reference Object.

  2. No, reason as 1).

  3. Phantom Reference doesn't apply in your example. By default, all instances are strong reference.

  4. 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.

like image 26
Buhake Sindi Avatar answered Oct 19 '22 22:10

Buhake Sindi