Java - Can objects which are executing methods be garbage-collected?

后端 未结 3 1991
春和景丽
春和景丽 2020-12-15 20:47

In Java, I\'ve done things like the following without thinking much about it:

public class Main {

    public void run() {
        // ...
    }

    public s         


        
3条回答
  •  孤街浪徒
    2020-12-15 21:12

    m is just a variable which has reference stored. This will be used by programmer to use the same object further to write logic on same object.

    While execution, program will be converted to OP-CODES / INSTRUCTIONS . These INSTRUCTION will have the reference to object(it is a memory location after all). In case m is present, location of object will be accessed via INDIRECT REFERENCE. If m is absent, the reference is DIRECT.

    So here, object is being used by CPU registers, irrespective of use of reference variable.

    This will be available till the flow of execution is in scope of main() function.

    Further, as per GC process, GC only removes objects from memory, once GC is sure that the object will not be used any further.

    Every object is given chance to survive a number of times(depends on situation and algorithm). Once the number of chances are over, then only object is garbage collected.

    In simpler words, objects which were used recently, will be given chance to stay in memory. Old objects will be removed from memory.

    So given your code:

    public class Main {
    
    public void run() {
        // ...
    }
    
    public static void main(String[] args) {
        new Main().run();
    }
    }
    

    the object will not be garbage collected.

    Also, for examples, try to look at anonymous class examples. Or examples from event handling in AWT / SWING.

    There, you will find a lot of usage like this.

提交回复
热议问题