text: Prev
  Java NetBeans Experts Index
  Headers
  Your browser does not support iframes.
  Re: String.valueOf() Memory Leak inside of thread.
  From:
  BLlewellyn@gmail.com
  Newsgroups:
  comp.lang.java.programmer
  Date:
  11 Aug 2006 05:20:53 -0700
  Message-ID:
  <1155298853.220730.110300@h48g2000cwc.googlegroups.com>
  Robert Klemme wrote:
  On 10.08.2006 21:52, BLlewellyn@gmail.com wrote:
  If anyone could shed some light, I'd appreciate it.
  I have a simple class with a main method. Inside the main method is a
  loop. Each iteration of that loop instantiates an anonymous thread
  whose run method contains a single line:
  String str = String.valueOf(1);
  This is causing a memory leak. If I change the line to read "String
  str = "String.valueOf("1"); there is no problem. Also, if I do
  something like: String str = "Hello world!"; there is also no problem.
  If I use String.valueOf(1); inside the loop but outside of the thread,
  there is no problem. Can anyone see why garbage collection is not
  occurring inside the thread?
  Thanks.
  --Bradley
  public class Main {
  public static void main(String[] args) {
  Thread thread = null;
  for ( int intLoop = 0; intLoop < 10000; intLoop++ ) {
  String myString;
  myString = String.valueOf(1);
  thread = new Thread() {
  public void run() {
  String str = String.valueOf(1);
  }
  };
  thread.start();
  thread=null;
  System.gc();
  }
  }
  }
  Some things to consider:
  1. IIRC System.gc() is just a hint. There is no guarantee that GC will
  actually start at that moment.
  2. There is no timely correlation between thread termination and
  System.gc(), i.e. the string might not yet have been created when gc()
  is invoked.
  3. Generally the JVM is very free to decide when GC occurs. I doubt it
  will create GC overhead if there is just a single (or a few) new objects
  on the heap.
  4. Your other examples do not exhibit the behavior you seem to observe
  because they don't create new instances.
  Kind regards
  robert
  Regarding number 1, using the NetBeans profiler, I'm seeing that each
  thread is a live object right up to the end of the program. Not sure
  if it will help, but according to the profiler there are 10,000 live
  instances of the anonymous class (Main$1), and over 10,000 instances of
  char arrays.
  Because of number 2, I've tried using a thread.join() to make sure the
  object is done being used.
  3. The profiler is showing that time is being spent in GC - is it
  possible that GC is running but decides the memory is not worth
  reclaiming?
  4. So basically you're saying that because String.valueOf("AString")
  just returns a pointer, there's no string actually being created? That
  makes sense.
  I'm thinking that if I can get rid of the char[] reference that's
  showing up in the profiler, the thread objects will go along with it.
  Any idea what I can do to clear it?
  Thanks again!
  --Bradley
  Generated by PreciseInfo ™, 'Thou):