Memory leak when using Threads?
I did an experiment and noticed a memory leak when I was using threads.. Here's what I did.
======================================
while( true )
{
Scanner sc = new Scanner(System.in);
String answer;
System.out.print("Press Enter to continue...");
answer = sc.next();
new TestThread();
}
========================================
And TestThead is the following
========================================
import java.io.*;
import java.net.*;
public class TestThread extends Thread
{
public TestThread() { start(); }
public void run() { }
}
=====================================
When I open windows Task Manager, every time a new thread starts and stops, the java.exe increases the Mem Usage.. Its a memory leak!? What is going on in this situation.. If I start a thread and the it stops, and then I start a new thread, why does it use more memory?
-Brian
[992 byte] By [
Conquerana] at [2007-11-27 11:59:39]

No, it's not a memory leak.
The VM simply hasn't GCed those threads yet because it didn't need to, or if it did, it didn't give the memory back to the OS (which it will rarely, if ever do).
jverda at 2007-7-29 19:26:50 >

while( true )
{
Scanner sc = new Scanner(System.in);
String answer;
System.out.print("Press Enter to continue...");
answer = sc.next();
}
======================================
Every time I enter something the mem usage increases.. Why?
It's the same exact thing.
You're creating new objects, and you haven't yet used up the heap space you've given the VM. If the VM hasn't run out of memory, it may decide not to do GC yet. It will do it when it has to. It may or may not do it sooner.
jverda at 2007-7-29 19:26:50 >

> MoveScanner sc = new
> Scanner(System.in);
out of the
> loop.Scanner sc = new Scanner(System.in);
> while (true) {
>...
>
That won't matter in any meaningful way.
Every loop iteration creates a new Scanner, but it also makes a Scanner eligible for GC, so the net memory requirement of the program is constant.
Now, of course, it's possible that the VM won't bother GCing until 64 MB worth of Scanners have been created, but we don't care about that. If we're allowing the GC 64 MB, then we don't care how it uses it or when it cleans it up.
jverda at 2007-7-29 19:26:50 >
