Closing/Despose of JFrame


J

Jesper Johnsen

How do I remove an object lets say a JFrame from memory?
I know that the garbage collector handles this - but this simple example does not release itself...
java.exe uses 10mb in the first wait stage, this increases to 20mb when the JFrame is shown, but the memory usage never returns to the initial 10mb.
So the garbage collector never removes the object from memory - why?

package jframetest;

import javax.swing.JFrame;

public class JFrameTest {

public static void main(String[] args) {
try{
Thread.sleep(5000);
}catch(Exception Ex){}
JFrame frame = new JFrame("Test");
frame.setVisible(true);
try{
Thread.sleep(5000);
}catch(Exception Ex){}
frame.setVisible(false);
frame.dispose();
frame = null;
while(1==1){
try{
Thread.sleep(100);
}catch(Exception Ex){}
}
}

}
 
Ad

Advertisements

M

markspace

How do I remove an object lets say a JFrame from memory?
I know that the garbage collector handles this - but this simple example does not release itself...
java.exe uses 10mb in the first wait stage, this increases to 20mb when the JFrame is shown, but the memory usage never returns to the initial 10mb.
So the garbage collector never removes the object from memory - why?


Why? Because the garbage collector never needs to remove the object.
You're using 20mb out of maybe 100mb to 1000mb or more? So the garbage
collector looks at that and says "plenty o' room left!" and doesn't run.

It's weird if you're used to having explicit control over object
destruction, but it works. More importantly it's efficient. Waiting,
and then removing lots of objects at once, is actually best for
throughput in the long run.

If you really need different behavior, check out Oracle's documentation
on tuning the garbage collector. You can choose what I believe is
called an incremental garbage collector which will work more like what
you are thinking.

<http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html>

Found via Google with search terms "java garbage collection tuning".
Learn to STFW.
 
S

Stefan Ram

Jesper Johnsen said:
JFrame frame = new JFrame("Test");

public class Main implements java.lang.Runnable
{ public void run()
{ java.lang.Runtime.getRuntime().gc();
try { java.lang.Thread.sleep( 1000 ); } catch( final java.lang.InterruptedException interruptedException ){}
java.lang.System.out.println( java.lang.Runtime.getRuntime().freeMemory() + " Bytes free without JFrame." );
for( int i = 0; i < 999; ++i )
{ java.lang.System.out.println();
javax.swing.JFrame frame = new javax.swing.JFrame();
frame.pack();
frame.setVisible( true );
try { java.lang.Thread.sleep( 1000 ); } catch( final java.lang.InterruptedException interruptedException ){}
java.lang.Runtime.getRuntime().gc();
try { java.lang.Thread.sleep( 1000 ); } catch( final java.lang.InterruptedException interruptedException ){}
java.lang.System.out.println( java.lang.Runtime.getRuntime().freeMemory() + " Bytes free with JFrame." );
frame.dispose();
frame = null;
try { java.lang.Thread.sleep( 1000 ); } catch( final java.lang.InterruptedException interruptedException ){}
try { for( int j = 1; ; j *= 2 )java.lang.String.valueOf( new byte[ j ] ); }catch( final java.lang.Throwable throwable ){}
try { java.lang.Thread.sleep( 1000 ); } catch( final java.lang.InterruptedException interruptedException ){}
java.lang.Runtime.getRuntime().gc();
try { java.lang.Thread.sleep( 1000 ); } catch( final java.lang.InterruptedException interruptedException ){}
java.lang.System.out.println( java.lang.Runtime.getRuntime().freeMemory() + " Bytes free without JFrame." ); }}

public static void main( final java.lang.String[] args )
{ try { javax.swing.SwingUtilities.invokeAndWait( new Main() ); }
catch( final java.lang.InterruptedException interruptedException ){}
catch( final java.lang.reflect.InvocationTargetException invocationTargetException ){} }}

15960272 Bytes free without JFrame.

15653064 Bytes free with JFrame.
15846872 Bytes free without JFrame.

15842304 Bytes free with JFrame.
15860504 Bytes free without JFrame.

15854872 Bytes free with JFrame.
15863136 Bytes free without JFrame.

15858568 Bytes free with JFrame.
15862568 Bytes free without JFrame.

15858000 Bytes free with JFrame.
15859232 Bytes free without JFrame.

15853240 Bytes free with JFrame.
15853808 Bytes free without JFrame.

15849240 Bytes free with JFrame.
15849720 Bytes free without JFrame.

15844040 Bytes free with JFrame.
15844560 Bytes free without JFrame.

15839992 Bytes free with JFrame.
15840472 Bytes free without JFrame.

15835904 Bytes free with JFrame.
15836384 Bytes free without JFrame.

15831720 Bytes free with JFrame.
15832256 Bytes free without JFrame.

15820216 Bytes free with JFrame.
....
 
L

Lew

markspace said:
Why? Because the garbage collector never needs to remove the object.
You're using 20mb out of maybe 100mb to 1000mb or more? So the garbage
collector looks at that and says "plenty o' room left!" and doesn't run.

It's weird if you're used to having explicit control over object
destruction, but it works. More importantly it's efficient. Waiting,
and then removing lots of objects at once, is actually best for
throughput in the long run.

If you really need different behavior, check out Oracle's documentation
on tuning the garbage collector. You can choose what I believe is
called an incremental garbage collector which will work more like what
you are thinking.

<http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html>

Found via Google with search terms "java garbage collection tuning".
Learn to STFW.

Shut the front window? :)

Both oracle.com and https://www.ibm.com/developerworks/java/ have
excellent articles and white papers on Java garbage collection, how it
works and how you can fine tune it.

Make sure you have a problem before you try to solve it, but it is
always useful to gather knowhow.

The default generational garbage collector works well, especially
for idiomatic Java. As Brian Goetz points out in his Developerworks
articles, the allocation cost in the heap is very tiny, on the order of
a dozen or so machine instructions. Deallocation is likewise not
very expensive for short-lived objects. Young objects live in the
young generation heap, and dead ones are ignored during
minor GCs.

If most objects are short-lived, as should be true if one follows
best practices for scoping variables, then most GC cycles will gather
about 3% of live objects, ignoring the 97% of unreachable ones.
This is a very fast copy and shouldn't burden your throughput
very much.

When objects survive enough minor GC cycles, they move to
the tenured generation, a different area of heap. These are only
collected during major GC cycles, which use different and somewhat
slower algorithms under default setup. The major cycles are the
ones we tend to notice. So if an object is going to survive to tenure,
aim to have it survive for a very long time thereafter. Otherwise
use idioms that help objects die young.

For example, dying young:

public class Example
{
Collection<Foo> foos = getSomeFoos();
public void run()
{
for (Foo foo : foos)
{
Bar bar = foo.obtainBar();
// do whatever with 'bar'
// 'bar' falls out of scope
// if nothing else points to the same object
// it is gone in the next minor GC
}
}
}

Dying old:

public class Example
{
Collection<Foo> foos = getSomeFoos();
Bar bar; // the elephant in the room
public void run()
{
for (Foo foo : foos)
{
bar = foo.obtainBar();
// do whatever with 'bar'
// 'bar' does not fall out of scope
// The last reference from the loop lasts as
// long as this instance does, and could
// tenure the 'Bar' it points to
}
}
}

So coding things the first way, which chance are is
more correct logically, tends to reduce the impact of
GC on performance. It tilts the GC towards very rapid,
almost negligible young-generation collections and
less toward the slower, more intrusive tenured-generation
collections.

Read widely and carefully. There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). Otherwise it's just superstition.
 
S

Stefan Ram

public class Main implements java.lang.Runnable

public class Main implements java.lang.Runnable
{ public void run()
{ for( ;; )
{ java.lang.System.out.println( java.lang.Runtime.getRuntime().freeMemory() + " Bytes free." );
javax.swing.JFrame frame = new javax.swing.JFrame();
frame.pack(); frame.setVisible( true ); frame.dispose(); frame = null; }}

public static void main( final java.lang.String[] args ) throws java.lang.Throwable
{ javax.swing.SwingUtilities.invokeAndWait( new Main() ); }}

The above program shows declining amounts of free memory for
some time. Then, a gc seems to be triggered, which reclaims
a part of the memory. After several such gcs, there is less
and less memory reclaimed and one feels that soon an
unrecoverable out-of-memory error will happen. But then a
real deep major gc seems to be triggered that seems to
reclaim all or nearly all of the memory! (I stopped it then,
maybe someone wants to have this running overnight?)
 
L

Lew

Stefan said:
Stefan said:
public class Main implements java.lang.Runnable

public class Main implements java.lang.Runnable
{ public void run()
{ for( ;; )
{ java.lang.System.out.println( java.lang.Runtime.getRuntime().freeMemory() + " Bytes free." );
javax.swing.JFrame frame = new javax.swing.JFrame();
frame.pack(); frame.setVisible( true ); frame.dispose(); frame = null; }}

public static void main( final java.lang.String[] args ) throws java.lang.Throwable
{ javax.swing.SwingUtilities.invokeAndWait( new Main() ); }}

The above program shows declining amounts of free memory for
some time. Then, a gc seems to be triggered, which reclaims
a part of the memory. After several such gcs, there is less
and less memory reclaimed and one feels that soon an
unrecoverable out-of-memory error will happen. But then a
real deep major gc seems to be triggered that seems to
reclaim all or nearly all of the memory! (I stopped it then,
maybe someone wants to have this running overnight?)

Also there are answers to other incarnations of this multipost
that go into how this all works.
 
Ad

Advertisements

A

Andreas Leitgeb

Lew said:
Dying old:
public class Example
{
Collection<Foo> foos = getSomeFoos();
Bar bar; // the elephant in the room
public void run()
{
for (Foo foo : foos)
{
bar = foo.obtainBar();
// do whatever with 'bar'
// 'bar' does not fall out of scope
// The last reference from the loop lasts as
// long as this instance does, and could
// tenure the 'Bar' it points to
}
}
}
[...]
There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). [...]

....or right after the loop in above "dying old"-Example, if for
whatever reason there really was some need to have "bar" as a
field, instead of as a local var within the loop.
 
L

Lew

Andreas said:
Lew said:
Dying old:
public class Example
{
Collection<Foo> foos = getSomeFoos();
Bar bar; // the elephant in the room
public void run()
{
for (Foo foo : foos)
{
bar = foo.obtainBar();
// do whatever with 'bar'
// 'bar' does not fall out of scope
// The last reference from the loop lasts as
// long as this instance does, and could
// tenure the 'Bar' it points to
}
}
}
[...]
There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). [...]

...or right after the loop in above "dying old"-Example, if for
whatever reason there really was some need to have "bar" as a
field, instead of as a local var within the loop.

True, but dangerous. If you are nulling out the reference after the loop
anyway, there is a low probability that a member variable is the right
scope. I can think of reasons why one might do that, but they all seem
like tangled and ill-advised code to me.

The scope and lifetime of the variable should match the scope and
lifetime of the need for its reference. The scenario you describe seems
to violate that. I say "seems to" because sure, there very well could be
cases for it. But they all would (or should) fit into the "scope and lifetime
should match" rule. So if you do see a situation where the scope is the
instance, and/or the lifetime matches that of the enclosing instance, then
a member variable is correct even should Lew feel that your code is tangled
and ill advised.

OTOH, you shouldn't be too quick to dismiss my insight into the matter.
 
J

John B. Matthews

public class Main implements java.lang.Runnable

public class Main implements java.lang.Runnable
{ public void run()
{ for( ;; )
{ java.lang.System.out.println(
java.lang.Runtime.getRuntime().freeMemory() + " Bytes free." );
javax.swing.JFrame frame = new javax.swing.JFrame();
frame.pack(); frame.setVisible( true ); frame.dispose(); frame = null;
}}

public static void main( final java.lang.String[] args ) throws
java.lang.Throwable
{ javax.swing.SwingUtilities.invokeAndWait( new Main() ); }}

The above program shows declining amounts of free memory for
some time. Then, a gc seems to be triggered, which reclaims
a part of the memory. After several such gcs, there is less
and less memory reclaimed and one feels that soon an
unrecoverable out-of-memory error will happen. But then a
real deep major gc seems to be triggered that seems to
reclaim all or nearly all of the memory! (I stopped it then,
maybe someone wants to have this running overnight?)

I cited a similar experiment here, using an artificially small heap to
exaggerate the effect:

<<https://groups.google.com/d/msg/comp.lang.java.help/ylUG68cHsWQ/h1FMBzKirkwJ>
 
G

Gene Wirchenko

[snip]
Read widely and carefully. There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). Otherwise it's just superstition.

Ah, not quite. In Visual FoxPro, at least in some versions, the
releasing of an object or an array with object references would result
in a memory leak. Setting to null was a workaround for that. I would
not be surprised if it happened in some other languages, too. However,
I would not do it unless it were required.

Sincerely,

Gene Wirchenko
 
R

Roedy Green

Otherwise it's just superstition.

quoting from http://mindprod.com/jgloss/null.html#GC

Null and Garbage Collection

Obviously, if you null a reference it becomes a candidate for GC
sooner. In ordinary Java code, it is most common that you would exit
the method almost immediately after such a nulling, so it buys you
nothing for local variables allocated during the method invocation.

However, if you had some very complicated method, it could pay to
null half-way through execution. But that being true is a symptom that
you probably would want to refactor the routine in two, which would
then most likely obviate the nulling.
--
Roedy Green Canadian Mind Products
http://mindprod.com
Why do so many operating systems refuse to define a standard
temporary file marking mechanism? It could be a reserved lead character
such as the ~ or a reserved extension such as .tmp.
It could be a file attribute bit. Because they refuse, there is no
fool-proof way to scan a disk for orphaned temporary files and delete them.
Further, you can't tell where the orhaned files ame from.
This means the hard disks gradually fill up with garbage.
 
Ad

Advertisements

L

Lew

Gene said:
Lew wrote:

[snip]
Read widely and carefully. There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). Otherwise it's just superstition.

Ah, not quite. In Visual FoxPro, at least in some versions, the

I'm sorry, Visual FoxPro?
releasing of an object or an array with object references would result
in a memory leak. Setting to null was a workaround for that. I would
not be surprised if it happened in some other languages, too. However,
I would not do it unless it were required.

I'm not so sure that rules of thumb derived from Visual FoxPro are
applicable here.

The urban legends to which I referred are specifically about Java.
 
G

Gene Wirchenko

Gene said:
Lew wrote:

[snip]
Read widely and carefully. There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). Otherwise it's just superstition.

Ah, not quite. In Visual FoxPro, at least in some versions, the

I'm sorry, Visual FoxPro?

A mid-level DBMS developed by Microsoft.
I'm not so sure that rules of thumb derived from Visual FoxPro are
applicable here.

I was countering your superstition statement.
The urban legends to which I referred are specifically about Java.

All you mentioned was that they were notable. You did not
mention Java. We do not discuss only Java here. And some cargo cult
programming can leap from language to language.

I have seen the set-to-null requirement stated for VFP (with a
reason) and VB 6 (without a reason). Now, you say it is in Java, too,
with limited times when it is necessary.

Sincerely,

Gene Wirchenko
 
Ad

Advertisements

L

Lew

Gene said:
Lew said:
Gene said:
Lew wrote:

[snip]

Read widely and carefully. There are some notable urban
legends out there, such as the advice to set all references
to 'null' when finished with them. There are specific times
to do so, such as when a collection such as a 'Stack' is
holding hidden references ("packratting", or the Java version
of a memory leak). Otherwise it's just superstition.

Ah, not quite. In Visual FoxPro, at least in some versions, the

I'm sorry, Visual FoxPro?

A mid-level DBMS developed by Microsoft.

I know what it is. I was questioning the relevance to a discussion of Java idioms.
I was countering your superstition statement.

Superstition is bad engineering and should be countered.
All you mentioned was that they were notable. You did not

The context was a discussion of Java.
mention Java. We do not discuss only Java here. And some cargo cult

This particular discussion was only about Java. The OP was asking about
removing JFrame instances from memory. That is not a general programming
question.

My point about 'null' was specific to Java because the topic was.

Don't be disingenuous.
programming can leap from language to language.

The reasons for or against setting to null are not the same, as
VFP is not a memory-managed language.
I have seen the set-to-null requirement stated for VFP (with a
reason) and VB 6 (without a reason). Now, you say it is in Java, too,
with limited times when it is necessary.

Different languages, different reasons, different worlds.

The point about avoiding superstition does cross universes.
 

Top