Can I force garbage collection?

D

D. Alvarado

I have read on this newsgroup that despite the "gc" method, one cannot
actually force garbage collection. I am using Java 1.3. and I was
wondering Iif I can induce it more quicly by setting certain objects
to "null" in my code? Does anyone else have any suggestions for
"forcing" garbage collection?

Thanks, - Dave
 
B

bugbear

D. Alvarado said:
I have read on this newsgroup that despite the "gc" method, one cannot
actually force garbage collection. I am using Java 1.3. and I was
wondering Iif I can induce it more quicly by setting certain objects
to "null" in my code? Does anyone else have any suggestions for
"forcing" garbage collection?

Why do you want to force garbage collection? The whole
point of a (decent, working ;-) garbage collector
is that it does the right thing without intervention.

Your only responsibility as a programmer is then to make
sure sure stuff you've finished with *IS* garbage (i.e.
no references remain)

BugBear
 
C

Chris Smith

D. Alvarado said:
I have read on this newsgroup that despite the "gc" method, one cannot
actually force garbage collection. I am using Java 1.3. and I was
wondering Iif I can induce it more quicly by setting certain objects
to "null" in my code? Does anyone else have any suggestions for
"forcing" garbage collection?

It's often said that using System.gc() does not force garbage
collection. However, the truth is more complicated. Certainly
System.gc() is the best shot you have at inducing a garbage collection
to occur, and you can be almost sure that one will happen if you call
that method. The API documentation for System.gc() says that "When
control returns from the method call, the Java Virtual Machine has made
a best effort to reclaim space from all discarded objects."

It's important to realize that that's not the same as saying that a
garbage collection will occur. For example, if there are some
concurrency constraints on garbage collection, then it may not be
possible to do any work at this time; in that case, a "best effort" is
no effort at all. It's also possible that the garbage collector is not
deferred; in other words, objects are garbage collected immediately, so
there may not be any work to be done.

What's more often meant by saying that you can't force garbage
collection is that there is no guarantee that an unreferenced object
will be freed by a call to System.gc(). There is, in fact, never a
guarantee that any unreferenced object will be freed, ever. For one
thing, conservative collectors will tend to retain a very small
percentage of objects accidentally, and the specification is designed to
allow them.

===

As for "setting certain objects to null": You may have your terminology
confused, or you may be confused about concepts. You can never set an
object to null. The null value is a possible value for a reference, and
indicates that it does not point to an object. When you set a reference
to null, the object it points to is still there but just isn't pointed
to by that reference any longer.

You should never set a reference to null just to encourage garbage
collection to happen sooner; it doesn't work, and it clutters your code.
There are a few rare instances where you may need to set a reference to
null to permit garbage collection to collect an object graph in the
first place, though. These situations, and a few other tips, are
mentioned at the bottom of http://jinx.swiki.net/59, which I wrote a
couple years ago to address this topic.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
M

Mike Schilling

Chris Smith said:
You should never set a reference to null just to encourage garbage
collection to happen sooner; it doesn't work, and it clutters your code.
There are a few rare instances where you may need to set a reference to
null to permit garbage collection to collect an object graph in the
first place, though. These situations, and a few other tips, are
mentioned at the bottom of http://jinx.swiki.net/59, which I wrote a
couple years ago to address this topic.

That's a nice writeup. Thanks.
 
D

Doug Pardee

To add to what Chris said:
The API documentation for System.gc() says that "When
control returns from the method call, the Java Virtual
Machine has made a best effort to reclaim space from
all discarded objects."
...
it may not be possible to do any work at this time;
in that case, a "best effort" is no effort at all.

Conversely, in modern Sun JVMs "best effort" means "maximum effort".
The JVM comes to a screeching halt while it runs a combination of
algorithms designed to root out every possible unused object from
anywhere that they might be hiding. The result is a GC cycle that
frequently can be measured in seconds instead of in milliseconds.
There is, in fact, never a guarantee that any unreferenced object
will be freed, ever. For one thing, conservative collectors will
tend to retain a very small percentage of objects accidentally,
and the specification is designed to allow them.

And in fact, the older Sun JVMs used such conservative collectors.

Modern Sun JVMs claim to have "accurate" collectors that can recover
all unused objects. However, there is a distinction between "can" and
"does". The JVM "can" recover all unused objects by using the
maximum-effort GC mentioned above, but ordinarily it uses partial
collections. These partial collections might overlook an unused object
here or there, but they run many times faster. Most overlooked garbage
will be picked up on a later collection cycle. The JVM won't declare
OutOfMemoryError without first trying a maximum-effort GC, so the
overlooked garbage doesn't affect the amount of memory available to
your program.
 
Joined
Sep 1, 2008
Messages
1
Reaction score
0
Attn: "BugBear"

Your cute little winking smiley's are irritating in the face of a serious question.

HONESTLY?

WHY *WOULDN'T* ANYONE WANT TO EXERT CONTROL WITH AN IRON FIST OVER A GARBAGE COLLECTOR?

YOU *ALWAYS* WANT TO CONTROL *EVERY* PART OF YOUR PROGRAM. FOOL.

ANYONE WHO ACCEPTS ANYTHING LESS IS COMPROMISING, AND DOOMED TO MEDIOCRITY.

Why? Why would someone want to force Garbage collection?

Why indeed?

Oh, I dunno. Maybe you've got a big fat clogged up heap from lots of preliminary processes.

BUT THEN. YOU'RE ABOUT TO EMBARK ON AN INTENSIVE PROCESS THAT WILL STRETCH YOUR RESOURCES TO THEIR LIMIT?

AND THE PROCESS HAPPENS FAST. MAYBE ON A SHARED SYSTEM.

GEE.

WOULDN'T IT BE NICE TO HAVE A NICE FRESH CLEAN BRAND NEW HEAP TO WORK ON. INSTEAD OF A FILTHY CONTAMINATED HEAP BRIMMING WITH CONTENTS UNKNOWN?

OH. BUT BY YOUR ASSESSMENT. I AM HANDCUFFED TO A BLOATED DISEASED BEACHED WHALE AND NO AMOUNT OF ELECTROSHOCK CATTLE PRODDING WILL GET IT BACK INTO THE WATER.

NO.

I HAVE TO SIT AND WAIT FOR A BLASTED CRANE TO COME AND HOIST IT ONTO A GARBAGE SCOW THAT WILL FOIST ITS USELESS BULK BACK INTO THE SEA

ONLY *THEN* WILL I GET TO EXPLORE THE OCEAN DEEP AGAIN. CHAPERONED BY A COW EYED BEHEMOTH.

BY THE WAY.

YOU NEVER ANSWERED HIS QUESTION ABOUT NULLS

THANKS FOR NOTHING, BUG BEAR.

-----

Which brings me to Chris Smith, Lead Software Developer and Technical Trainer, MindIQ Corporation.

"You should never set a reference to null just to encourage garbage collection to happen sooner; it doesn't work, and it clutters your code."

"NEVER."

Really. Are you serious?

This flies in the face of nearly EVERYTHING else I've been reading EVERYWHERE else.

Am I to believe that YOU, Chris Smith, are correct and that every other piece of information I'm encountering is wrong?

I'm pretty firmly convinced that you are dealing ATROCIOUS advice, likely to sabotage and ruin the efforts of the ignorant everywhere.

"Cluttered" code that works. is WAY better the code that APPEARS clean but is doomed, doomed, doomed to fail miserably

I've found that clean, easy to read code is often the harbor of meager results.

Contrast this with the many examples of horrendously dense unintelligible and muddy code that will deliver powerful results

Appearance of code IS NOT an indicator of performance.

Ugly *LOOKING* code can be horrible or wonderful without ANY relationship to its human-readable qualities

IF YOU DON'T KNOW WHAT'S CAUSING YOUR PROBLEM?

TRY LITERALLY EVERYTHING UNTIL IT WORKS.

DON'T WORRY ABOUT "Oh dear, it might look UGLY, GORSH!"

No, that is not how you solve problems.

If you are dealing with leaks there could be a number of different potential causes, but.

WHAT THESE FOOLS FAIL TO NOTICE IS THAT YOU MAY FIND YOURSELF RECLAIMING MEMORY ONE WAY OR ANOTHER.

YOU MIGHT FIND YOUR SELF TAKING THE WHOLE SYSTEM DOWN AND BRINGING IT ALL THE WAY BACK UP.

JUST TO WIPE CLEAN YOUR MEMORY.

BECAUSE YOU CAN'T FORCE GARBAGE COLLECTION.

YOU MIGHT FIND YOUR SYSTEM HANGING, ENDLESSLY

STARING BACK AT YOU LIKE A LISTLESS ZOMBIE

BECAUSE SOMEONE ELSE'S LOG IS CLOGGING UP YOUR DIGESTIVE TRACT.

YOU'VE GOT A *PROBLEM*

AND MAYBE THERE ARE 15,000 CLASSES CONSISTING OF 18 TRILLION-AND-A-HALF LINES OF CODE

MAYBE THERE ARE PROPRIETARY BLACK-BOX JARS INVLOVED

YOU DIDN'T CAUSE THE PROBLEM, AND NO ONE KNOWS WHO DID. OOPS!

MAYBE THE PERSON WHO CAUSED THE PROBLEM QUIT THREE YEARS AGO AND STAFF HAS TURNED OVER, COMPLETELY, FIVE TIMES SINCE THEN.

If something is broken, YOU RIP IT APART, DOWN TO ITS BARE CHASIS UNTIL YOU FIND THE CAUSE.

THAT MY FRIENDS, IS WHAT TROUBLESHOOTING IS.

If, you've tried everything BUT setting references to nulls?

And nothing has worked yet?

Give the nulls a try. Trust your gut. Trust your suspicions.

If it doesn't work? Well then.

Obviously you have your answer.



But to quote the REST of the internet:
--------------------------------------

Garbage consists of objects that aren't referenced by anything. There are no static, instance, or local variables that remain, either directly or indirectly.

Assign null to variables that you are no longer using. This will, if there are no other references, allow this memory to be recycled (garbage collected).



AND AGAIN:
----------

An object is eligible for garbage collection when no object refers to it.

An object also becomes eligible when its reference is set to null. (Actually all references to the object should be null for it to be eligible.)



AND AGAIN:
----------

We can prevent memory leaks by watching for some common problems. Collection classes, such as hashtables and vectors, are common places to find the cause of a memory leak. This is particularly true if the class has been declared static and exists for the life of the application. and many times member variables of a class that point to other classes simply need to be set to null at the appropriate time.


AND AGAIN:
----------

If you are done with an object set it to null, don’t just let it sit there, because eventually, you may very well run into issues where you eat up all of your memory and the garbage collector just can’t handle it.



AND AGAIN:
----------

...In this example, the object referenced continues to be strongly referenced, at least until the run method returns. That might not happen for a long time. Because invisible objects can't be collected, this is a possible cause of memory leaks. If you run into this situation, you might have to explicitly null your references to enable garbage collection.
 
Joined
Sep 30, 2010
Messages
1
Reaction score
0
ECHO_CHAMBER Fail

@ECHO_CHAMBER

Yeah, you're right about "cute little winking smiley's" (sic). They're so annoying.

I know this is a 2 year old post, but you're a douchebag. You flame someone for not answering the question and then you spend an hour and a half writing up a post that barely answers the question and doesn't cite any sources. And while you're trying to make everyone feel stupid, you just look stupid for writing in all caps which IS WAY MORE ANNOYING THAN ANY AMOUNT OF EMOTICONS. EMOTICONS, BY THE WAY, IS THE PROPER WORD FOR "SMILEY'S".

Here's some "smiley's" for you. (No apostrophe needed in smileys, BTW.)


:( :D :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger: :finger:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top