memory management and java
@fourthdimension (135)
United States
November 11, 2008 11:06am CST
Hey All
I'm using java in a project I'm working on, but hate the fact that java gives you so little control over its memory consumption. So I had a few questions... is it possible to delete variables in java when they're no longer needed but while the program is still operating within the variable's scope? Second, is there a way to manually initiate garbage collection?
Thanks.
3 responses
@fmjasper (6)
• China
18 Nov 08
Unfortunately it is hardly possible. But it is always a good habit to explicitly set a reference to an object to null when you finish using it though. You can call System.gc() but it is not guaranteed whether the garbage collection will be done on the invoking. No more worry about the memory recycle, that's what Java is meant to be but for a developer moved from C++, it is inconvenient.
@mr_mlk (364)
•
29 Dec 08
Re the nulling a reference. This is NOT good practice. Good practice is to have a nice tight scope and let the reference fall out of scope and be eaten when the JVM wants to. 99% of the time nulling a reference has no befit, and clutters your code making it hard to read.
@mr_mlk (364)
•
29 Dec 08
I'd have to disagree with the opening statement. Java gives you all the control you need. If items are outliving their scope, make the scope smaller or if you really really must, set ALL the references to the object to null. The GC WILL clear it when it has to.
If you are running out of memory - use a profiler. Find out what still has a hold on the object.
@fmmik2x (17)
• Philippines
21 Nov 08
have you tried reconfiguring the heap spaces for your application?
try setting the maximum and the minimum heap spaces for your java application by adding the following options on your java command:
maximum heap space: -Xmx{value}m
minimum heap space: -Xms{value}m
example: java -Xmx256m -Xms128m MyMainApp
if you've got a PermGen Exception, just adjust its permanent heap size by adding these options:
max perm size: -XX:MaxPermSize={value}m
min perm size: -XX:PermSize={value}m
FYI, the java heap spaces compose of 3 generation. The New Gen, Old Gen, and the Permanent Gen. New gen are for objects that lives in a short span of time. If these objects lives long, the garbage collector will move them to the Old Gen. While the Permanent Gen are for objects that lives permanently.
Hope this help.