1

Assume a condition inside a Thread while true condition as shown below

package com;

import java.util.Date;

public class Tester extends Thread {

    public void run() {
        Date d = new Date();
        while(true)
        {   
              d = new Date();
        }
    }
}

will this code be a issue or not ??

Issue because : as it will create too many Date objects ??

Not an Issue because : as there no longer exists a reference to the old date object after the new assignment so therefor the garbage collector should cleanup the old object

I guess this will be not an issue , please suggest me if this code is fine .

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • Have you tried it? You could write a little test program and use [VisualVM](http://docs.oracle.com/javase/7/docs/technotes/guides/visualvm/) to monitor the heap size. – beny23 Jul 26 '13 at 06:31
  • [This](http://stackoverflow.com/questions/2620533/why-make-short-and-long-lived-objects-a-difference-in-garbage-collection) might help – MadProgrammer Jul 26 '13 at 06:32
  • depends on heap size and gc i guess. – Sachin Verma Jul 26 '13 at 07:01

2 Answers2

4

The GC will collect all the garbage that the loop creates, but you still have an infinite loop that does nothing useful and will bring one of your codes to 100% CPU usage doing nothing useful, and that will force the GC to constantly collect useless junk. That's quite an issue to me.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • master is always a master , thanks a lot I have one condition where I need to put it inside my code so first trying with an simple standalone . – Pawan Jul 26 '13 at 06:34
-3

I think this code could be an issue.

Depends on how often the garbage collector runs. The program will create as many Date objects as possible and the old objects are deleted when the garbage collector runs.

If you put an "System.gc();" after d = new Date(); then it would be no problem i think.

schaeferpp
  • 109
  • 10