Ofek Ron
Ofek Ron

Reputation: 8580

Java GC and Memory usage tracking

I know that the GC releases memory of objects that have no longer references to, but is there an effcient way to check if i do have references to no longer used objects?

tips on how to avoid leaving references to no longer used objects would be greatly aprriciated.

Is using the Windows Task Manager any help in this situation? if so, tips on how to criticize my program using it would help too.

thanks.

Upvotes: 1

Views: 372

Answers (3)

FrVaBe
FrVaBe

Reputation: 49341

You may find the article What is a “Memory leak” in Java? useful (I don't know the tool that get's advertised here).

I don't know how to find referenced but not used objects - but sometimes also objects that can be garbage collected will have an impact on your program - if you create masses of them and provoke often GC.

To track the GC activity you can simple use the java non standard option -Xloggc:<file>. This will log the GC activity to the given file. You will get a first impression how busy your application is with garbage collecting.

I hope this is a useful information for you although I did not answer your question.

Upvotes: 1

Ingo Kegel
Ingo Kegel

Reputation: 47975

"No longer used" objects are garbage collected. "Using" means holding a strong reference. The problem is with objects you do not intend to use, but that are still strongly referenced by mistake.

Only Java profilers like VisualVM or JProfiler can help you to find these objects.

A screen cast that shows how to find a memory leak with JProfiler is available here.

Disclaimer: My company develops JProfiler.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

The check is simple. You are still using all objects you have references to.

A common problem with "memory leaks" is adding objects to collections and forgetting to clean them up when they are no longer needed. A way around this problem is to use WeakReferences or a collection which uses these e.g. WeakHashMap. These are cleaned up when there is no longer a reference elsewhere.

IMHO, Windows Task manager is more likely to confuse than help here. ;)

Using VIsualVM or a commercial memory profiler like YourKit is the best way to examine your memory consumption.

Upvotes: 3

Related Questions