简体   繁体   中英

Collections, singletons, garbage collection

I have following code:

public void method1() {
    Emp e1 = new Emp();
    Emp e2 = new Emp():
    Emp e3 = new Emp();
    method2(e1, e2, e3);
}

public void method2(Emp... emps) {
    List<Emp> emps = new ArrayList<>();
    for(final Emp emp : emps) {
        emps.add(emp);
    }
    // do some task with list
}

So when method2 returns will emps be garbage collected? Or we need to explicitly remove elements. Would like to understand in perspective of memory leaks.

Any pointers appreciated greatly.

There is no definite time when garbage collection will run. Whenever there is no reference to an object it will become eligible for garbage collection .

When a method is called in Java it goes inside the stack frame. When the method is popped from the stack, all its members die. Hence they become eligible for gc. The objects that were created inside it becomes unreachable or anonymous after method execution and thus becomes eligible for garbage collection.

Short answer : Yes, "emps" will be Garbage Collected, and No, you do not need to explicitly remove elements in Java.

Longer answer : Assuming you are new to Java and Garbage Collection (maybe coming from a C++ background?) then the answers so far may be skipping the very simple answer you are looking for. As some have pointed out, your posted code would not quite compile in Java, so we can't quite give a perfect answer. That said, I assume you are really just asking whether we have to explicitly free memory in Java: No, we do not.

From Java Garbage Collection Basics :

In a programming language like C, allocating and deallocating memory is a manual process. In Java, (the) process of deallocating memory is handled automatically by the garbage collector.

Garbage Collection is a complicated topic, but you can essentially trust that the JVM will identify " which objects are in use and which are not " on some interval, and will delete " the unused objects " on some interval. Therefore, you will likely not open up any "memory leaks" in your program if you allow the JVM to see that objects are unused -- in other words, don't hold onto objects when you don't need them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM