P
Paul J. Lucas
The Javadoc for Object.finalize() (at least in the 1.4.2 JDK)
says in part:
For example, the finalize method for an object
that represents an input/output connection
might perform explicit I/O transactions to
break the connection before the object is
permanently discarded.
But this isn't really a good thing to use finalize() for in
practice since it might take a very long time for an object's
finalize method to be called (if ever). During that time, it's
possible that the system might run out of file descriptors, or
sockets, or whatever.
You might say, "Well, just call close() explicitly." The
problem with that advice is that it doesn't work in cases where
you want objects to hang around as long as possible -- but no
longer.
For example, if I have some class that uses a file as part of
its implementation and I want to keep them around as long as
possible but still allow them to be reclaimed if memory gets
low, then I would use SoftReferences to the objects.
This works great, but only from a memory perspective. Since
the garbage collector doesn't know anything about file
descriptors (or any other non-memory resource), it's can't know
that garbage collection should be triggered if the number of
available file descriptors (or whatever resource) becomes low.
So what's a good way to handle finite, non-memory resources?
- Paul
says in part:
For example, the finalize method for an object
that represents an input/output connection
might perform explicit I/O transactions to
break the connection before the object is
permanently discarded.
But this isn't really a good thing to use finalize() for in
practice since it might take a very long time for an object's
finalize method to be called (if ever). During that time, it's
possible that the system might run out of file descriptors, or
sockets, or whatever.
You might say, "Well, just call close() explicitly." The
problem with that advice is that it doesn't work in cases where
you want objects to hang around as long as possible -- but no
longer.
For example, if I have some class that uses a file as part of
its implementation and I want to keep them around as long as
possible but still allow them to be reclaimed if memory gets
low, then I would use SoftReferences to the objects.
This works great, but only from a memory perspective. Since
the garbage collector doesn't know anything about file
descriptors (or any other non-memory resource), it's can't know
that garbage collection should be triggered if the number of
available file descriptors (or whatever resource) becomes low.
So what's a good way to handle finite, non-memory resources?
- Paul