Re: String.valueOf() Memory Leak inside of thread.
On 11.08.2006 14:20, BLlewellyn@gmail.com wrote:
Robert Klemme wrote:
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.
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.
Well, then GC decided to not collect them.
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?
Yes. There are some nice articles about how GC works on Sun's site. I
suggest you grab those and read through them - pretty interesting stuff.
GC is a quite complex process and the short story is that the JVM is
pretty free as to /when/ do GC and /which objects/ it will collect.
Especially will an object stay around even after a method terminated as
long as the stack frame is not overridden. This could be the case for
"myString" in run() because every thread gets its own stack.
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.
Exactly.
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?
I have no idea what you mean here. The reference path is the other way
round, the char[] inside the String is referenced via the Thread.
Freeing the char[] or the String doesn't impact a thread's reachability
in any way. Note that threads are special and so the JVM might collect
them at different points in time than ordinary objects.
Cheers
robert