java - objects and garbage collection.
If I have an ArrayList<Object> of objects, like: ``` ArrayList<StringBuilder> al = new ArrayList<>(); for(int i = 0; i < 100; i++) { al.add(new StringBuilder(String.valueOf(i) + ") Hello World.")); } ``` Would doing something like ``` al = new ArrayList<StringBuilder>(); ``` clear it from memory, and thus clear the RAM? I know it will clear the arraylist, but I'm not sure it will actually clear it from memory. thanks
Garbage collection is a very complicated process and it could take a book to explain it properly. But the most basic principle question is this one: what can be garbage collected ?An object is marked for garbage collection when there is no more reference to it. Consider your program: You're building 100 String object, and their (only) references are contained in an ArrayList object. Then you delete the content of this ArrayList, but the ArrayList itself is still referenced by the "al" variable. This means that, at the end of this code, the 100 Strings are eligible for garbage collection. The ArrayList, on the other hand, will not be eligible because the "al" variable still is in scope. But you have to know that eligible for GC doesn't mean that the memory is cleared right away. The JVM runs the GC when appropriate, and you have no way to know when. So your only concern should be to keep the variables scopes as small as possible so that GC can perform well when it is necessary.
Join our real-time social learning platform and learn together with your friends!