Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java anonymous classes and Garbage Collector

Lets assume that some class is not reachable, but there are another anonymous classes generated by the class which are reachable. Could the first one be removed by the Garbage Collector?

Example:


class Outer {
  public Object getInner() {
    return new Object() {};
  }
}

...

Outer outer = new Outer();
Object inner = outer.getInner();

// Could the "outer" instance be removed here considering that "inner" is using below?
like image 410
Ilya Lakhin Avatar asked Mar 02 '12 09:03

Ilya Lakhin


People also ask

What are anonymous classes in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

Can anonymous class have multiple methods?

You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.

Which class is used in garbage collection?

gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.

Is there garbage collector in Java?

Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM. Each JVM can implement garbage collection however it pleases; the only requirement is that it meets the JVM specification.


1 Answers

No, the outer instance is still reachable in this case, since every non-static inner class has an implicit rerefence to its outer class instance.

like image 52
JB Nizet Avatar answered Oct 13 '22 20:10

JB Nizet