{"id":1380,"date":"2013-02-16T13:46:02","date_gmt":"2013-02-16T18:46:02","guid":{"rendered":"http:\/\/unitstep.net\/?p=1380"},"modified":"2013-02-16T13:46:02","modified_gmt":"2013-02-16T18:46:02","slug":"java-final-finally-and-finalize","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2013\/02\/16\/java-final-finally-and-finalize\/","title":{"rendered":"Java: final, finally and finalize"},"content":{"rendered":"

One of the most popular Java interview “screener” questions is often, “What is the difference between final<\/strong>, finally<\/strong> and finalize<\/strong>?”<\/em> In fact, it occurs so much that one should probably have the answer memorized. But knowing when to use these features is better than just knowing what they mean.<\/p>\n

<\/p>\n

The final<\/code> keyword – classes and methods<\/h2>\n

When used on a class, final<\/code> prevents the class from being extended. Similarly, when final<\/code> is used on a method, that method cannot be overridden in any subclass. <\/p>\n

This is mainly done for reasons of security and consistency: If you have a class whose methods you count on to provide predictable results, you may want to prevent that class from being extended so that someone cannot substitute a subclass that behaves differently to a consumer that expects your original class. The same may go for certain methods on a class.<\/p>\n

But generally, you should not be marking classes\/methods as final<\/code> unless you have a compelling argument for it. The reason is that using final<\/code> may unnecessarily constrain the design and hamper future developers who may have a legitimate reason for wanting to extend your class. Though I prefer composition over inheritance, it’s not a choice I would want to force on everyone else, nor do I believe it’s always the right choice.<\/p>\n

In particular, you should not be marking classes\/methods as final<\/code> just for some perceived performance benefit. In many cases you won’t gain a thing performance wise, but will be unnecessarily be constraining your design.<\/p>\n

One reason you shouldn’t<\/em> refrain from marking a method as final<\/code> is for mockability; mocking frameworks like JMockit<\/a> allow you to easily mock out final<\/em> methods, so don’t let that affect your design decisions.<\/p>\n

The final<\/code> keyword – variables<\/h2>\n

When used on variables, final<\/code> essentially means that the variable can only be assigned once. For class\/static members, this is when the class is loaded; for instance members, this is when an instance of the class is created; for local variables, it is usually when the variable is declared. Method parameters can also be declared as final<\/code>.<\/p>\n

As opposed to the use of final<\/code> on classes\/methods, I usually like using final<\/code> for most variables, as it can decrease the complexity of code by decreasing the chances for state changes. Once you know that a local variable is final<\/code>, if it’s primitive, you can be sure its value won’t change; if it’s an object, you can be sure you’ll always be dealing with the same object.<\/p>\n

Furthermore, the use of final<\/code> on member variables ensures that you know they’ll be assigned once and only once: At object creation. <\/p>\n

Some people may think that the use of final variables is superfluous, but I think it’s a good defensive programming technique. This article<\/a> sums up my viewpoints nicely.<\/p>\n

finally<\/h2>\n

As opposed to the final<\/code> keyword, which is completely optional and not strictly necessary to use, you should almost always be using the finally<\/code> keyword in Java when dealing with closeable resources. (This is true before Java 7, as Java 7 introduces some nice syntactic sugar that can remove the need to use finally<\/code>)<\/p>\n

Here is a contrived example:<\/p>\n

InputStream inputStream = null;\r\ntry {\r\n  inputStream = new FileInputStream(new File(\"TEST.XML\"));\r\n  final int read = inputStream.read();\r\n  \/\/ Do other stuff with the stream...\r\n} finally {\r\n  if (null != inputStream) {\r\n    inputStream.close();\r\n  }\r\n}<\/code><\/pre>\n

In this example, we initialize the inputStream<\/code> within a try<\/code> block. If anything goes wrong with reading from the stream, an exception will be thrown (which we don’t handle here, for brevity) but before it is allowed to propagate, the code within the finally<\/code> block will be executed, ensuring that if the stream has been opened, it will be closed. This will prevent a resource leak from happening.<\/p>\n

Here is how that code could also look in Java 7:<\/p>\n

try (final InputStream inputStream = new FileInputStream(new File(\"TEST.XML\"))) {\r\n  final int read = inputStream.read();\r\n  \/\/ Do other stuff with the stream...\r\n}<\/code><\/pre>\n

As you can see, the amount of “boilerplate” is reduced as we don’t need to have an explicit finally<\/code> block anymore. This is known as a “try-with-resources” statement<\/a>, where an object that implements Closeable\/AutoCloseable<\/code> is declared and initialized with the try<\/code> statement and automatically closed no matter what the outcome of the statements within the try<\/code> block. I would suggest using this unless your code needs to be JDK 6 compatible. <\/p>\n

finalize()<\/h2>\n

As opposed to final<\/code>, which you may use and finally<\/code>, which you will certainly have to use in JDK 6 and below, you will almost never need to implement or override Object.finalize()<\/code><\/a>.<\/p>\n

The finalize()<\/code> method is called by the garbage collector (GC) determines that there is no longer anyway for the object to accessed; this means the object is eligible for finalization, which means the GC can begin the process of making the object finalizable, finalized and then reclaimed. Generally any Object that does not have a Strong reference<\/a> is eligible. <\/p>\n

There is generally no need to override the default finalize()<\/code> method; if your class opens resources then it should be responsible for properly closing\/releasing them by using try-catch-finally<\/code> as outlined above, or you should make your class implement Closeable<\/code> so that clients\/callers of your class can ensure its proper closure.<\/p>\n

You could, in theory, use finalize()<\/code> as a “safety net” of sorts to mitigate the effects of bad clients\/callers not calling close()<\/code> on your class by ensuring that internal resources are closed\/released in finalize()<\/code> but you should never rely on this<\/strong>.<\/p>\n

Additionally, if you are overriding finalize()<\/code> you must take care to ensure that you don’t “leak” a reference to the object to the “outside world”, or else this may prevent the object from being garbage collected, resulting in a potential memory leak! (i.e. don’t pass a reference to this<\/code> to any external objects during finalize()<\/code>)<\/p>\n

In general, if you are going to implement\/override finalize()<\/code>, you should have a very specific reason and be very careful in how you do so.<\/p>\n

The final word<\/h2>\n

I hope you enjoyed this summary of final, finally and finalize(). Learning these concepts is pretty fundamental to having a good understanding of Java as a whole.<\/p>","protected":false},"excerpt":{"rendered":"

One of the most popular Java interview “screener” questions is often, “What is the difference between final, finally and finalize?” In fact, it occurs so much that one should probably have the answer memorized. But knowing when to use these features is better than just knowing what they mean.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[64,197,137],"tags":[397,399,398,450,438],"_links":{"self":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/1380"}],"collection":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/comments?post=1380"}],"version-history":[{"count":25,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/1380\/revisions"}],"predecessor-version":[{"id":1426,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/1380\/revisions\/1426"}],"wp:attachment":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/media?parent=1380"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/categories?post=1380"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/tags?post=1380"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}