CodeGym /Java Course /Module 2. Java Core /The finalize method, closeable interface, and try-with-re...

The finalize method, closeable interface, and try-with-resources statement (Java 7)

Module 2. Java Core
Level 9 , Lesson 4
Available
The finalize method, closeable interface, and try-with-resources statement (Java 7) - 1

"Hi, Amigo!"

"I just decided to discuss the finalize() method with you."

"If you remember, finalize() is a special method that is called by an object before
the garbage collector destroys it."

"This method's main purpose is to free up used external non-Java resources by closing files, I/O streams, and so on."

"Unfortunately, this method doesn't live up to our expectations. The Java virtual machine can postpone destroying an object, as well as calling the finalize method, as long as it wants. Moreover, it doesn't guarantee that this method will be called at all. There are loads of situations where it doesn't get called, all in the name of «optimization»."

"I've got two references for you:"

Joshua Bloch has written a good article about this method: link
I'll paraphrase a short excerpt:

  1. finalize() can only be used in two cases:
    1. For verifying or cleaning up resources with logging.
    2. When working with native code that is not critical to resource leaks.
  2. finalize() makes the GC 430 times slower at cleaning up objects
  3. finalize() might not be called
If I say in an interview that finalize is a harmful and dangerous crutch whose very existence is confusing, would I be right?

"Well, that made my day, Ellie."

"Java 7 has a new statement to replace the finalize method. It's called try-with-resources. It isn't really a replacement for finalize, rather it is an alternative approach."

"Is it like try-catch, but with resources?"

"It's almost like try-catch. The things is, unlike the finalize() method, the finally block in a try- catch-finally statement is always executed. Programmers have also used this technique when they've needed to free up resources, close threads, etc.

"Here's an example:"

InputStream is = null;
try
{
 is = new FileInputStream("c:/file.txt");
 is.read(…);
}
finally
{
 if (is != null)
 is.close();
}

"Regardless of whether the try block executed properly or there was an exception, the finally block will always be called, and it's possible to release occupied resources there."

"So, in Java 7, the decision was made to make this approach official, like so:"

try(InputStream is = new FileInputStream("c:/file.txt"))
{
 is.read(…);
}

"This special try statement is called try-with-resources (similar to how collections have an alternate for called foreach)."

"Notice that after the try there are parentheses where variables are declared and objects are created. These objects can be used inside the try block indicated by the curly brackets. When the try block is done being executed, regardless of whether it ended normally or there was an exception, the close() method will be called on any objects created inside the parentheses."

"How interesting! This notation is far more compact than the previous one. I'm not sure I understand it yet."

"It isn't as difficult as you think."

"So, can I specify the class of each object in the parentheses?"

"Yes, of course, otherwise the parentheses would be of little use."

"And if I need to call another method after exiting the try block, where do I put that?"

"Things are a bit more subtle here. Java 7 introduces the following interface:"

public interface AutoCloseable
{
 void close() throws Exception;
}

"Your class can implement this interface. And then you can use its objects inside a try-with-resources statement. Only such objects can be created inside the parentheses of a try-with-resources statement for «automatic closure»."

"In other words, I need to override the close method and write code in it to «clean up» my object, and I can't specify another method?"

"Yep. But you can specify several objects—just separate them with a semicolon:"

try(
InputStream is = new FileInputStream("c:/file.txt");
OutputStream os = new FileOutputStream("c:/output.txt")
)
{
 is.read(…);
 os.write(…);
}

"That's better, but not as cool as I'd hoped."

"It's not that bad. You'll get used to it. With time."

Comments (13)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Ranganathan Kasiganesan Level 75, Chennai, India Expert
7 April 2024
Excellent. The second question is amazing. I never thought that the java.sql classes could be even used to fetch data from a class's object. Kudos to CodeGym team.
Abhishek Tripathi Level 72, Rewa, India Expert
25 October 2023
Bro, I freaked out because the second question asked us something which is not going to compile at all.
阿狼 Level 32, Zhengzhou, China
2 July 2022
d25
ジョーンズJ Level 47, United States
19 January 2022
"Well, that made my day, Ellie." typo, It's supposed to say Well, that made my day, Kim
Justin Smith Level 41, Greenfield, USA, United States
10 December 2021
The funny thing about this lesson is that we had code in tasks from Java Core that used this syntax. It was just never explained to us.
Mike McKenna Level 25, Wilmington, United States
6 March 2021
https://java2blog.com/java-try-with-resources/ more information about try-with-resources
Andrei Level 41
24 March 2021
The link you provided also has catch, whereas the try with resources exemplified above does not use catch. What is the difference?
Romain Level 26, Paris, France
26 March 2021
yo the catch method allows you to do specific action in case there is an exception thrown Otherwise you have to propagate it, by nomming it after keyword "throws" placed after your method name Advice you to read again lessons 3 and 4 of Syntax quest level 9
MaGaby2280 Level 41, Guatemala City, Guatemala
9 June 2020
This try with resources explanation doesn´t really help for solving the tasks
fzw Level 41, West University Place, United States
17 April 2020
Finalize has been deprecated since Java9 "So, can I specify the class of each object in the parentheses?" "Yes, of course, otherwise the parentheses would be of little use." "And if I need to call another method after exiting the try block, where do I put that?" Description is confusing. When we declare objects, we always specify class of object, right? And there is no way to write code after the try block to call methods?
Fadi Alsaidi Level 34, Carrollton, TX, USA
25 July 2020
I am hoping that you might have an insight ito this now that you are level 41. I am confused about the same exact thing.
fzw Level 41, West University Place, United States
5 August 2020
ha ha, I never thought about coming back and review the material. Thank you. Now I feel it should be "And if I need to call another method on the objects defined in the try blockafter exiting the try block, where do I put that?" Now this makes sense to me
Romain Level 26, Paris, France
18 March 2021
I think it too, and the answer can be this one : https://www.studytonight.com/java/try-with-resource-statement.php# "In Java 7, try-with-resource was introduced and in which resource was created inside the try block. It was the limitation with Java 7 that a connection object created outside can not be refer inside the try-with-resource. In Java 9 this limitation was removed so that now we can create object outside the try-with-resource and then refer inside it without getting any error." But I think it doesn't include files or streams, which I think are logically closed after use. On the other hand for our class objects implementing closeable or autoclosable this can be of interest because we define ourselves what their closure implies, so depending on that our object can still be exploitable.