3

Within a class that extends Thread, consider the following example:

public void run() {
   while (workToDo) {
        JSONObject json = new JSONObject(getNextMap());
        publishJSON(json.toString());
        //  thread sleep
   }
}

Is each instance of json still referenced as long as the thread is running, or are they freed each time new is called? Should this be moved to a method, i.e. publishJSON(getJson(getNextMap())?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
coolhouse
  • 33
  • 2
  • 1
    After every loop iteration, it will be available for GC as it goes out of scope. – Sotirios Delimanolis Aug 01 '13 at 14:25
  • They are freed when the GC thinks they should be. Note that when reaching the last sentence of the `while` loop, the object reference hold by `json` variable will be marked for garbage collection. – Luiggi Mendoza Aug 01 '13 at 14:26
  • @assylias Can you expand? – Sotirios Delimanolis Aug 01 '13 at 14:29
  • @SotiriosDelimanolis there are weird border cases where an out-of-scope, unreachable variable can't be collected. See for example: http://stackoverflow.com/questions/13531004/java-outofmemoryerror-strange-behaviour - note that I don't think that other post applies to the OP's case. – assylias Aug 01 '13 at 14:34
  • @assylias Right. _invisible_ state. In that case, always safer to `null` the variable. – Sotirios Delimanolis Aug 01 '13 at 14:56

1 Answers1

4

To have a reference to object then it must be a local used variable (while in local scope) or contained in a member variable of a class instance.

I don't see any of the two in your example since after each while iteration the local variable can't be referenced anymore. So, unless you do something with json that saves a reference to it elsewhere, they are eligible for garbage collection.

Mind that this doesn't imply that the GC will collect the no-more-referenced instances after every iteration since its behavior is not predictable from a developer point of view. You just know that eventually they'll be collected.

Jack
  • 131,802
  • 30
  • 241
  • 343