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?
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.
You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.
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.
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.
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.
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