I think you're making the mistake of thinking of finalizers as
destructor.
No, i'm not. I'm quite explicitly not. As i took pains to point out in my
post.
The right way to do this is just to close the object.
Yes.
And if the client code forgets to close the object? Then what? You just
leak the native resource? Please tell me whether you'd be happy to let
that happen, and if not, how you'd present it. Remember - this is if the
client code forgets to explicitly close.
You don't need finalizers at all if you aren't using weak references.
Eh? Finalizers and weak references are basically completely unrelated. In
fact, to an extent, they're alternatives, so if you *are* using weak
references, you don't need finalizers!
The whole point of my post was about dealing with the case where the
object isn't or can't be explicitly closed.
Try-catch-finally. The "finally" portion is always run.
You didn't read what i wrote. There are times when the lifetime of an
object is not tied to a lexical scope. In that situation, you *cannot* use
a try-finally block. It is *not possible*.
Maybe you don't understand how this can be so. Let's try an example.
Consider a server for doing online hotel booking. The application is all
about showing the user a list of hotels, in the same city or whatever, and
letting them compare rooms and prices, then letting them make a choice and
book a room (or several rooms, etc).
The actual hotel booking is handled by a legacy mainframe app, with which
you communicate using a native library. The library lets you open a handle
on a particular hotel, make queries and reservations for that hotel using
the handle, and close the handle. You can only have one handle to a given
hotel open at once. Opening handles is expensive. Use of a handle is
threadsafe. You wrap the handle in a class, which has methods to interact
with it, and a close method. So far so good.
Now you write the client-facing part of the code. There are servlets or
whatever out front, and then a layer of business objects. You have a
session object (could be a stateful EJB, could just be a pojo) which holds
the conversational state. Part of that state is a set of handles to the
hotels which are being looked at. Handles are expensive, but threadsafe,
so you share the handle for a given hotel between all the client sessions
which are looking at that hotel. The session object has business methods
which are called by the servlet layer when user requests come in, and
return with responses. Sessions are created and destroyed automatically by
the servlet container in response to users coming and going.
I'm happy to ignore handle creation for now, but here's the question: how
do you deal with the closing of handles? Where, pray tell, do you put your
try-finally block?
tom