- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
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 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 {}
- Related Articles
- How to make an object eligible for garbage collection in Java?
- Garbage collection in Java
- Java Garbage collection
- How to force garbage collection in C#?
- How can we call garbage collection (GC) explicitly in Java?
- Using the finalize() method in Java Garbage Collection
- When will be an object eligible for garbage collection?
- How to create an object from class in Java?
- Garbage Collection in Python
- How does garbage collection work in Python?
- How to prevent Cloning to break a Singleton Class Pattern in Java?
- Garbage collection(GC) in JavaScript?
- How does Garbage Collection work in Lua Programming?
- How to access the object of a class without using the class name from a static context in java?
- Destroying Objects (Garbage Collection) in Python

Advertisements