Java – set reference = null in the finally block?

One of my colleagues set null in the finally block I think this is nonsense

public Something getSomething() {
    JDBCConnection jdbc=null;
    try {
        jdbc=JDBCManager.getConnection(JDBCTypes.MysqL);
        ...
    }
    finally {
        JDBCManager.free(jdbc);
        jdbc=null; // <-- Useful or not?
    }
}

What do you think?

Solution

You are right. JDBC is a local variable, so when the getsomething () method returns JDBC, it will be out of range and qualified for garbage collection, which is actually the same as setting it to null Therefore, it makes no sense to set the variable to null when the next line of code is out of range

A good practice is to limit variables to the minimum required. For example, if you only need a variable in a for loop and then declare it in a for loop, it will be eligible for garbage collection when the code exits the for loop In this way, in addition to reducing the complexity of the method, you even need to set the local variable to null, which is conducive to making your code more modular, easier to read and maintain

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>