Re: threads and GUIs
LC's No-Spam Newsreading account wrote:
I thought that doing an instance of SwitchPinger each time (with the
idea to run things in a loop, currently instead iterations beyond the
first are activated manually) would somehow waste memory.
Java manages memory for you. When an instance no longer has any references to
it reachable from the live program, i.e., the instance becomes unreachable, it
is eligible for garbage collection (GC) to delete it.
In a loop like:
for ( Item item : stuff )
{
Foo foo = new Foo();
foo.process( item );
}
a new 'Foo' is created within each iteration of the loop. Clearly there are
no other references to that new instance (unless 'process()' does something
weird - we'll assume not). As each loop iteration closes, the 'foo' reference
goes out of scope and the 'Foo' instance becomes unreachable. GC will
eventually collect and destroy the unreachable references if it thinks the
memory is needed.
Java is optimized for short-lived objects, ones that become unreachable
quickly. If the 'Foo' instance were created outside the loop and refilled
each time, the loop could be slower and memory pressure would likely increase,
not decrease. That's because Java GC uses different strategies for short- and
long-lived objects.
Java doesn't actually have memory leaks. What we Java folks call "leaks" are
actually the opposite - memory references that are not released, leaving
objects still reachable, ergo uncollectible, eventually causing the dreaded
'OutOfMemoryError' ("OOME" colloquially).
As in paths to inner peace, the guiding principle for harmonious object
management in Java is, "Let it go."
--
Lew