The inner class has an implicit reference to the outer class and may cause a memory leak

Having learned about the inner class, I understand that it has an implicit reference to the outer class.

But my teacher told me that the best way is not to use the inner class, prefer to use a static inner class. Because the inner class may leak memory.

Can anyone explain about this?

+5
source share
1 answer

In response to your comment (it would be unreadable if I posted it in the comments) where it belongs. An example of using the inner class outside the outer.

public class Dog { String name; } public class HugeKennel { Double[] memmoryWaste = new Double[10000000]; public List<Dog> getDogs() { SneakyDog trouble = new SneakyDog("trouble"); return Arrays.asList(trouble); } class SneakyDog extends Dog { SneakyDog(String name) { this.name = name; } } } 

somewhere else in your code

 List<Dog> getCityDogs() { List<Dog> dogs = new ArrayList<>(); HugeKennel k1 = ... dogs.addAll(k1.getDogs()); HugeKennel k2 = ... dogs.addAll(k2.getDogs()); return dogs; } .... List<Dog> cityDogs = getCityDogs(); for (Dog dog: dogs) { walkTheDog(dog); } // even though the Kenels were local variables in of getCityDogs(), they cannot be removed from the memory, as the SneakyDogs in the list are still referencing their parent kennels. //from now on, until all the dogs are not disposed off, the kennels also have to stay in the memory. 

Thus, you do not need to access the inner class through its parrent class, as soon as the inner object is created, it can be used like any other object and can be "leaked out" into its container class, as in the example above, when the list of dogs will be contain links to dogs, but each dog still "knows" about its kennel.

A related example from StackTrace was related to a typical use case when inner classes are created as "anonymous inner classes", but this is the same problem. If you pass a reference to any instance of the inner class, you also pass the reference to the outer class.

+5
source

Source: https://habr.com/ru/post/1214405/


All Articles