Is it possible to force garbage collection in Java, even if it is tricky to do? I know about System.gc();
and Runtime.gc();
but they only suggest to do GC. How can I force GC?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Using the Java™ Virtual Machine Tool Interface (JVM TI), the function
will "Force the VM to perform a garbage collection." The JVM TI is part of the JavaTM Platform Debugger Architecture (JPDA).
There is some indirect way for forcing garbage collector. You just need to fill heap with temporary objects until the point when garbage collector will execute. I've made class which forces garbage collector in this way:
Usage:
I don't know how much this method is useful, because it fills heap constantly, but if you have mission critical application which MUST force GC - when this may be the Java portable way to force GC.
It would be better if you would describe the reason why you need garbage collection. If you are using SWT, you can dispose resources such as
Image
andFont
to free memory. For instance:There are also tools to determine undisposed resources.
Use
Runtime.getRuntime().gc()
or use utility methodSystem.gc()
JVM specification doesn't say anything specific about garbage collection. Due to this, vendors are free to implement GC in their way.
So this vagueness causes uncertainty in garbage collection behavior. You should check your JVM details to know about the garbage collection approaches/algorithms. Also there are options to customize behavior as well.
(Sorry I can't add this as a comment as I don't have enough reputation points.)
I once interviewed at an image processing company for a Java job (even though I didn't have any/much java experience.)
Their tale of woe that was interesting to me, was their program would allocate a HUGE buffer for image. Once, they were done with the image and memory, they would deference it. Knowing that they really needed to recover the memory sooner than later, they tried to use an explicit call to Java gc() during a quiet time of the program. Unfortunately, gc() is merely a suggestion to the Java runtime and had no effect.
As I recall, they ended up having to recycle the memory themselves.