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())?

5
  • 1
    After every loop iteration, it will be available for GC as it goes out of scope. Commented Aug 1, 2013 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. Commented Aug 1, 2013 at 14:26
  • @assylias Can you expand? Commented Aug 1, 2013 at 14:29
  • @SotiriosDelimanolis there are weird border cases where an out-of-scope, unreachable variable can't be collected. See for example: stackoverflow.com/questions/13531004/… - note that I don't think that other post applies to the OP's case. Commented Aug 1, 2013 at 14:34
  • @assylias Right. invisible state. In that case, always safer to null the variable. Commented Aug 1, 2013 at 14:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I wasn't sure if scope changed each pass through the loop.
You don't know that. GC may never run at all. You know that the object is eligible for connection under the conditions stated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.