
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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