java - When does object go out of scope if no variable is assigned? -


when object of type list, occupying memory, become eligible garbage collection, variable holds reference list ? in case of code below, there no variable assigned it.

case 1:

for (integer : returnlist()) {      system.out.println(i); } 

in case of code like:

case 2:

list list = returnlist(); (integer : list) {      system.out.println(i); }    list = null; 

we can take control of gc, there ways take care of in first case when no variable assigned ?

to summarize:

  1. what mechanism of referrence, without reference variable list case 1?

  2. does list eligible gc'd when stack frame popped ?

  3. any way speed eligibility gc'ing ?

what mechanism of referrence, without reference variable list case 1?

there implicit reference list. can seen understanding enhanced for translated into:

for(iterator e = returnlist().iterator(); e.hasnext(); ) {     integer = (integer)e.next();     system.out.println(i); } 

here, e has reference iterator on returnlist, itself has reference returnlist. thus, returnlist rooted long e rooted only true while control in for loop. when control leaves for body, e eligible collection, returnlist eligible collection.

of course, of assuming that

  1. the owner of returnlist isn't maintaining reference return value.
  2. the same list hasn't been returned caller , other caller isn't maintaining reference same list.

does list gc'd when stack frame popped ?

not necessarily. eligible collection when jvm can determine referrent has no rooted references it. note not collected.

any way speed gc in case 1.

it can't collected sooner control leaving for loop. might collected after control leaves for loop. let jvm worry this.

note can attempt manual garbage collection via

system.gc(); 

but note might exhibit worse behavior because if triggers garbage collection, might full garbage collection. note jvm can ignore request. might wasting lot of cpu cycles here. note on system infinite memory, garbage collector never needs run. on such system, requesting garbage collector complete waste of cpu cycles if garbage collector obeys request.

let jvm manage garbage collections. algorithms highly tuned.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -