3 ms·
Question to people who have used finalizers in GC languages: can you describe what you used them for?
by cousin_it 13y ago
Question to people who have used finalizers in GC languages: can you describe what you used them for?
- anonymoushn 13y agoI worked on some extremely filthy project that, among other things, sent data over the network in a constructor and finalizer so that a clone of a subset of the program's state could be maintained remotely. You just had to inherit from this class and suddenly you would have a clone all the time.
- anonymous 13y agoLook at the FileInputStream and FileOutputStream classes in Java. The finalize method in them makes sure the file is closed when the object is reclaimed, to prevent file handle leaking. It's not particularly effective a strategy for managing file handles unfortunately and if you forget to close your output streams, your program will crash with "too many open files".
- bcoates 13y agoIf you call out to a C-style library through the FFI that's expecting a cleanup call, you should call it in both a user-accessible close() function and the finalizer. I think the easiest way to think about it is, "finalizers don't prevent handle leaks, they sometimes clean up a handle leak that already happened". I'm not sure if any debugger environments give a warning when a finalizer gets run due to GC but they ought to--it always indicates a programmer error.