Reputation: 11
My program uses several Swingworker
threads and I need to free up each thread's memory after it completes. Whether my thread terminates by completing the doInBackground()
method or gets stopped by cancel()
, the thread itself stays there (it still shows in Jconsole).
I dereference the Swingworker
instance and force a garbage collection, but my Java process never releases any memory (e.g. as shown by the Windows Task Manager).
How can I completely remove a terminated Swingworker
thread?
Or how could I free up the memory which it allocates at several places during some complex processing?
Any advice is most appreciated. Thanks.
Upvotes: 1
Views: 1717
Reputation: 313
I have a similar issue. I use multiple SwingWorker threads to do some computation and Windows Task Manager reports that the number of threads in java.exe never goes down, always up. If the task was completed normally or cancelled doesn't seem to matter at all.
From what I now, the number of threads depends on the amount of RAM of the machine and the maximum address space available to a process (in 32-bit operating systems that value is 2 GB).
From what I know, sometimes these are not the only limits. In Windows (XP or later) I heard that, although a limit is not explicitly imposed by the OS, processes that have more than 1000 threads tend to crash for no apparent reason.
I will try to use my program to start and cancel those SwingWorker threads until the number is very big. I'm very curious what will happen (I have XP 32 bit and 1 GB RAM).
The thing is that, this might be a real issue. If on some operating systems and/or hardware platforms, there are thread count issues, then someone that is using such a program for very long periods of time (not exiting for hours) might have some very bad experiences...
Upvotes: 0
Reputation: 346377
You probably don't have to do anything and your code is already working as desired. Teh thread is still there because it's part of a thread pool, but that does not mean the memory used by the SwingWorker object is not released.
Java process never releases any memory (e.g. as shown by the Windows Task Manager).
The JVM (at least the Sun/Oracle one) is generally very reluctant to return memory to the OS and will do so only if more than 70% of the heap memory is unused. This can be tuned using the -XX:MaxHeapFreeRatio
command line options (but generally should be left as it is).
For diagnosing a program's memory usage, it's much more useful to use a tool like VisualVM that can display used and free heap memory. I don't know JConsole well but would expect it to have that feature as well.
Upvotes: 1