Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to prevent object of a class from garbage collection in Java?
If a object is no more referenced by a live reference then it becomes eligible for garbage collection. See the example below −
Example
public class Tester{
public static void main(String[] args) {
test();
}
public static void test(){
A a = new A();
}
}
class A {}
When test() method complete execution, the a object is no more referenced and is eligible for garbage collection. Java garbage collector will deallocate the object when it runs.
To prevent garbage collection, we can create a static reference to an object and then this object will not be garbage collected. See the example below −
Example
public class Tester{
private static A a;
public static void main(String[] args){
test();
}
public static void test(){
a = new A();
}
}
class A {} Advertisements
