Câu hỏi phỏng vấn Java
Câu hỏi

When is the finalize() called? What is the purpose of finalization?

Câu trả lời

The finalize() method in Java is called by the garbage collector on an object when it determines that there are no more references to the object, making the object eligible for garbage collection. However, it's important to note that the invocation of finalize() is not guaranteed; the garbage collector may or may not call it, and if it does, it is typically the last thing it does before reclaiming the memory occupied by the object[1][2][3][5][6][8][9][10].

The primary purpose of finalization is to provide an opportunity to perform cleanup operations before an object is destroyed. This can include releasing non-memory resources that the object holds, such as file handles, network connections, or database connections. Essentially, finalization offers a safety net to free up resources that the object acquired during its lifetime[1][2][3][4][5][6][7][8][9][10].

However, relying on finalization for cleanup is generally unreliable and discouraged for several reasons:

  1. Unpredictability: There is no certainty regarding the timing of when the finalize() method will be called. The garbage collector is under no obligation to execute it promptly or even at all[3][4][5][8][10].
  2. Performance Issues: Finalization can lead to performance penalties. Objects that override finalize() may be delayed in their garbage collection, which can lead to memory and resource leaks[8][10].
  3. Deprecation: As of Java 9, the final...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is an Java Applet?

middle

If an object reference is set to null , will the Garbage Collector immediately free the memory held by that object?

junior

When does an Object becomes eligible for Garbage Collection in Java ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào