Is the Java garbage collector going to take care of variables declared in loops?

If I have:

for (int i; i != 100; i++) {
    ArrayList<String> myList = buildList();
    //... more work here
}

Should I set myList to zero at the end of my loop to get the GC to recover the memory it uses for myList?

+5
source share
6 answers

GC will automatically clear any variables that are no longer in scope.

A variable declared inside a block, such as a for loop, will only be within the scope of this block. As soon as the code exits the block, GC will delete it. This happens as soon as the loop iteration ends, so the list becomes suitable for garbage collection as soon as each loop iteration ends.

, i .

, , . , , .

+10

, ! Java GC , , , .

+6
+4

GC , . GC-.

i myList . for ( ), , . . myList null ( GCing ). GC myList, , .

GCed, .

+3

, for-. JLS 14.14.1.

BasicForStatement:
    for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement

...

Statement:
    StatementWithoutTrailingSubstatement
    ...

StatementWithoutTrailingSubstatement:
    Block
    EmptyStatement
    ExpressionStatement
    ...


Block:
    { BlockStatementsopt }

BlockStatements:
    BlockStatement
    BlockStatements BlockStatement

BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement

, , (, ). , , , . , for. :

 public void someMethod() {

     {
         List<String> myList = new ArrayList<String>();
         System.out.println(myList);
     }
     System.out.println(myList.size()); //compile error: myList out of scope
 }

, , . , , , ( , , ).

+3

You don’t need to worry about trash. Java GC will automatically do this. But my suggestion is that, as a good developer, you should do a practice to free garbage. Since the GC will take some time. Therefore, taking care of ourselves, we will definitely increase productivity.

0
source

All Articles