finalize() Method in Java जावा में फाइनलाइज़ मेथड

In Java, when an object holds resources like file handles, fonts, or native system resources, we often need a mechanism to clean them up before the object is destroyed. This process is known as Finalization.

जावा में जब कोई ऑब्जेक्ट फाइल हैंडल, विंडोज फॉन्ट्स जैसे रिसोर्सेज से जुड़ा होता है, तो ऑब्जेक्ट के नष्ट होने से पहले इन रिसोर्सेज को मुक्त करना ज़रूरी होता है। इस प्रक्रिया को Finalization कहते हैं।

For this, Java provides a special method called finalize(). You can define this method in your class to perform cleanup tasks before the object is garbage collected.

इसके लिए जावा में एक विशेष मेथड finalize() होता है। इस मेथड को अपनी क्लास में डिफाइन करके हम वह कार्य कर सकते हैं जो किसी ऑब्जेक्ट के नष्ट होने से ठीक पहले किए जाने चाहिए।

This method is called automatically by the Garbage Collector just before an object is destroyed. The garbage collector runs periodically and destroys objects that no longer have any active references.

यह मेथड ऑब्जेक्ट के नष्ट होने से पहले स्वतः ही गार्बेज कलेक्टर द्वारा कॉल किया जाता है। गार्बेज कलेक्टर समय-समय पर चलता है और उन ऑब्जेक्ट्स को हटा देता है जिनके पास कोई वैध रेफरेंस नहीं बचा होता।

🔧 Syntax / प्रारूप:

protected void finalize() throws Throwable {
// Finalization code
}

📘 Example / उदाहरण:

class Sample {
int id;
Sample(int id) {
this.id = id;
}
protected void finalize() throws Throwable {
System.out.println("Object with ID " + id + " is destroyed.");
}
public static void main(String[] args) {
Sample obj1 = new Sample(101);
Sample obj2 = new Sample(102);
obj1 = null;
obj2 = null;
System.gc(); // Request garbage collection
}
}

In the above example, the finalize() method is used to display a message when the object is destroyed. Although System.gc() only suggests garbage collection, it may or may not run immediately.

इस उदाहरण में finalize() मेथड तब कॉल होती है जब ऑब्जेक्ट नष्ट होता है। System.gc() गार्बेज कलेक्टर को कॉल करने का अनुरोध करता है, लेकिन यह तुरंत काम करे, इसकी गारंटी नहीं होती।


Note:

  • From Java 9 onwards, finalize() is deprecated due to performance and reliability concerns. Alternatives like try-with-resources or Cleaner API are recommended.

  • जावा 9 से finalize() को deprecated कर दिया गया है क्योंकि यह प्रदर्शन और विश्वसनीयता पर नकारात्मक प्रभाव डाल सकता है। इसके स्थान पर try-with-resources या Cleaner API का उपयोग करना बेहतर माना जाता है।

Comments

Popular posts from this blog

What is a Web Browser? वेब ब्राउज़र क्या है?

Java's Support System जावा का सहयोगी तंत्र

The Internet and Java इंटरनेट और जावा का सम्बन्ध