- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we call garbage collection (GC) explicitly in Java?
When there are no more references to an object, the object is finalized and when the Garbage Collection starts these finalized objects get collected this will done automatically by the JVM. We can call garbage collection directly but it doesn't guarantee that the GC will start executing immediately.
We can call the Garbage Collection explicitly in two ways
- System.gc() method
- Runtime.gc() method
The java.lang.Runtime.freeMemory() method returns the amount of free memory in the Java Virtual Machine (JVM). Calling the gc() method may result in increasing the value returned by the freeMemory.
Example
public class GarbageCollectionTest {
public static void main(String args[]) {
System.out.println(Runtime.getRuntime().freeMemory());
for (int i=0; i<= 100000; i++) {
Double d = new Double(300);
}
System.out.println(Runtime.getRuntime().freeMemory());
System.gc();
System.out.println(Runtime.getRuntime().freeMemory());
}
}
Output
15648632 13273472 15970072
Advertisements