When is a Java local variable eligible for GC?

前端 未结 6 1423
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 01:11

Given the following program:

import java.io.*;
import java.util.*;

public class GCTest {

    public static void main(String[] args) throws Exception {
             


        
6条回答
  •  执念已碎
    2021-01-06 01:59

    What are you observing that you find strange? Each time you execute run(), you create a new instance of Test. Once run completes, that instance of test is out of scope and eligible for garbage collection. Of course "eligible for garbage collection" and "is garbage collected" are not the same thing. I'd expect that if you run this program, you'd see a bunch of finalize messages scroll by as invocations of run complete. As the only console output I see is these messages, I don't see how you would know which instance of Test is being finalized when you see each message. You might get more interesting results if you added a println at the beginning of each invocation of run, and maybe even added a counter to the Test object that gets incremented each time a new one is created, and which is output with the finalize message. Then you could see what was really happening. (Well, maybe you're running this with a debugger, but that could also obscure more.)

提交回复
热议问题