preface

This speed-reading article comes from regular interviewers final, Finally, Finalize. To be honest, I don’t quite understand why these three are put together. It’s totally irrelevant! But take it as it comes.

Today, let’s talk about the respective scenarios of Final, Finally and Finalize.

To the chase

primers

Small A: MDove, RECENTLY I found that many articles compare final, finally and Finalize together. With all due respect to my stupidity, I really don’t know what they have to do with each other.

MDove: Can’t you see the relationship? This is not: these three are kaspersky, Pakistan and The clown Paki relationship, there is a Kiba relationship!

Little A: Huh? .

MDove: There is no relation between them. I guess people think they look alike, so let’s compare them together. Today let’s not talk about the relationship between the three, let’s talk about the characteristics of each one. Start with the most common final:

final

MDove: Final is a very basic keyword for us. Final can be used to modify classes, methods, and variables.

  • Final class, which means no extension can be inherited.
  • 2. Final methods cannot be overridden.
  • 3. Final variables cannot be modified.

MDove: Let’s focus on point 3, the so-called unmodifiable for base types is indeed unmodifiable. In the case of reference types, reassignment is impossible. That is, you cannot change the reference address. However, as a reference type, its internal contents can be modified if they are not final, as in:

final List<String> arryList = new ArrayList<>();
arryList.add("AAA");
arryList.add("BBB");

List<String> unmodifiableArrayList = List.of("AAA"."BBB");
unmodifiableArrayList.add("CCC");
Copy the code

MDove: Final only allows arryList references not to be reassigned, but the behavior of arryList objects is not affected by final, which means add is fine. If we want objects to behave immutable, we use list.of (), which creates objects that are inherently immutable, so the last add will throw an exception at run time.

MDove: We all know that final variables need to be displayed to give it an initial value. Here’s a test for you, if you don’t want to assign it directly, what do you do?

Little A: I guess… It needs to be in the constructor, right?

MDove: Yes, that’s true:

fianl int num;
final int num2 = Awesome!;
public Test(a){
    num = Awesome!;
}
Copy the code

MDove: In the previous article, we mentioned that these two notations are actually equivalent for compiled class files.

MDove: There’s another interesting thing about final. In many articles, final can improve performance in certain scenarios. For example, using final might help the JVM inline methods, improve the compiler’s ability to perform conditional compilation, and so on. To be honest, there is no need to consider such a hypothesis.

finally

MDove: Let’s talk about finally. When it comes to finally, you can’t escape a try-catch. Finally is Java’s mechanism for ensuring that important code must be executed. Most commonly used: try-catch-finally to release resources, secure unlock, etc. Such as:

FileInputStream inputStream = null;
try {
    inputStream = new FileInputStream(new File("test"));
    System.out.println(inputStream.read());
} catch (IOException e) {
    throw new RuntimeException(e.getMessage(), e);
} finally {
    if(inputStream ! =null) {
        try {
            inputStream.close();
        } catch (IOException e) {
            throw newRuntimeException(e.getMessage(), e); }}}Copy the code

MDove: One point here is that try-finally is also possible. I don’t recommend omitting the catch. Because we stepped in that hole a while ago. The exceptions captured in our project are generally passed out through the Error CallBack in the catch to Log. When we were chasing a Bug, we found that there were no logs at all. Later, I found out that there was a Bug. After the try exception, I did not do any processing directly finally, so I could not see the Log, which wasted a lot of time.

MDove: of course, the try-with-resources statement added in Java7 is more recommended for releasing resources in finally. Simple and efficient ~ for example:

try (FileInputStream inputStream = new FileInputStream(new File("test"))) {
    System.out.println(inputStream.read());
} catch (IOException e) {
    throw new RuntimeException(e.getMessage(), e);
}
Copy the code

So these two things are equivalent. Of course, this is just grammar candy

MDove: Of course there are some crazy questions that ask you when finally is not executed. This case is not executed:

try {
    System.exit(1);
} finally{system.out. println(" The program is dead, I still execute a thread ~ "); }Copy the code

MDove: As you can see, finally cannot execute any operation that can cause the program to stop. It really doesn’t make sense to be honest…

MDove: Finally let’s talk about Finalize.

finalize

MDove: To be honest, Finalize is not often used in our daily development and is not recommended. Even in Java9, object.Finalize () is explicitly marked as deprecated!

MDove: As for Finalize, the initial function of finalize is to let CG call out an object with confidence when CG wants to retrieve it, “Report, I can save it again!” . But because of this, the JVM does extra processing on it. Finalize also becomes an obstacle to CG collection, which leads to multiple garbage collection cycles before the object can be collected.

MDove: I don’t know Much about Finalize, so let’s stop here for the time being. If you’re still interested, check out the analysis.

MDove: I don’t know if you’ve learned a little bit about all three. To be honest, all three of them need to know OJBK, why they’re designed, and how they’re used. It can be applied flexibly to the business. Excessive pursuit of some “strange technology and lewdness”, but lost the meaning of the design itself.

Little A: There’s no end to learning. I think I chose the wrong industry.

The end

I am a fresh graduate, recently and friends maintain a public account, the content is that we in the transition from fresh graduate to the development of this way stepped on the pit, as well as our step by step learning records, if interested in friends can pay attention to it, together with fuel ~