Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Force Garbage Collection in Java? [duplicate]

Possible Duplicate:
Forcing Garbage Collection in Java?

Can I Force Garbage Collection in Java by any means?

System.gc() is just a suggestion.It's useless.

When I know for sure that some resources won't be used any more,why can't I force to clean them?

Just like delete() in C++ and free() in C?

When there are lots of resources that can't be reused,this can really suck the performance.All that we can do is sleep().

Any solutions?Thanks

like image 563
Jacob Avatar asked Mar 02 '12 03:03

Jacob


2 Answers

Nope, System.gc() is as close as you can get. Java isn't C or C++, the JVM manages memory for you, so you don't have that kind of fine grained control. If you set objects you're no longer using to null, or loose all references, they will get cleaned up. And the GC is pretty smart, so it should take good care of you.

That said, if you are on a unix box, and force a thread dump (kill -3), it'll pretty much force garbage collection.

like image 158
Michael Avatar answered Oct 30 '22 03:10

Michael


You shouldn't be trying to force GC - if you are running low on memory then you have a memory leak somewhere. Forcing GC at that point won't help, because if you are holding a reference to the object then it still won't be garbage collected.

What you need to do is solve the real problem, and make sure you are not holding references to objects you are not using any more.

Some common culprits:

  • Holding lots of references in a large object graph that never get cleared up. Either set references to null when you don't need them any more, or better still simplify your object graph so it doesn't need all the extra long-term references.
  • Caching objects in a hashmap or something similar that grows huge over time. Stop doing this, or use something like Google's CacheBuilder to create a proper soft reference cache.
  • Using String.intern() excessively on large numbers of different strings over time.
  • References with larger scope than they need. Are you using an instance variable when it could be a local variable, for example?
like image 30
mikera Avatar answered Oct 30 '22 02:10

mikera