It seems like people got tired of manual memory management, so they invented garbage collection, and life was reasonably good. But what about every other resource types? File descriptors, sockets, or even user created data like database connections?
This feels like a naive question but I cannot find any place where anyone has asked it. Let's consider file descriptors. Say a program knows that it will only be allowed to have 4000 fds available when it starts. Whenever it performs an operation that will open a file descriptor, what if it would
- Check to make sure that it isn't about to run out.
- If it is, trigger the garbage collector, which will free a bunch of memory.
- If some of the memory freed held references to file descriptors, close them immediately. It knows the memory belonged to a resource because the memory tied to that resource was registered into a 'file descriptor registry', for lack of a better term, when it was first opened.
- Open a new file descriptor, copy it into new memory, register that memory location into the 'file descriptor registry' and return it to the user.
So the resource would not be freed promptly, but it would be freed whenever the gc ran which includes at the very least, right before the resource was about to run out, assuming it isn't being entirely utilized.
And it seems like that would be sufficient for many user defined resource cleanup issues. I managed to find a single comment here that references doing cleanup similar to this in C++ with a thread that contains a reference to a resource and cleans it up when only it has a single reference remaining (from the cleanup thread), but I can't find any evidence of this being a library or part of any existing language.