Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×

Comment Re:Wrox Press (Score 1) 558

You're right of course. My original description of finalizers was rather simplistic. The best advice I can give to new Java developers (or C# developers, come to think of it), is to completely avoid using finalizers to dispose of non-memory resources such as file streams, sockets and database connections. It's just too easy to introduce bugs this way, and they're often the type of bug that's hard for a new developer to track down the cause.

There are two common alternatives to using finalizers. The first is to avoid retaining references to non-memory resources, wherever possible. As bckrispi mentioned above, it's good practice to close sockets and file streams as soon as you've finished with them (or in the case of database connections, relinquish then to a common pool).

The second is to expose lifecycle management methods on your class, typically by providing a close() or dispose() method, which passes the responsibility of lifecycle management to the code using your class. Needless to say, the first option is definitely preferred over the second.

In 15 years of Java and C# coding, I can honestly say that the only time finalizers have been useful is in trying to detect the case where client code hasn't invoked the relevant close() or dispose() method, in order to issue a debug logging call so that this can be trapped, and then make a final attempt to call close() or dispose() within the finalizer and hope for the best.

Slashdot Top Deals

And it should be the law: If you use the word `paradigm' without knowing what the dictionary says it means, you go to jail. No exceptions. -- David Jones

Working...