Friday, January 16, 2009

Memory Management != Resource Management

On Jeff Atwood's blog, in a post about garbage collection and modern programming languages he states "I view explicit disposal as more of an optimization than anything else." I think it is a mistake to take this point of view. In modern languages we use objects to represent system resources in addition to just data. In those situations it isn't good enough to just let the garbage collector clean up after you.

I can't count the number of times I've come across bugs that were the result of a developer assuming the garbage collector would close a file handle for him and that code failing randomly because the garbage collector hadn't run yet and file was locked. For example, I've seen a lot of Java methods that open a FileInputStream, read all the data, and return without closing the stream.

Garbage collection is great for memory management because it doesn't usually matter when memory is freed. Other system resources, on the other hand, usually need to be freed deterministically. The Disposable pattern handles this situation pretty well.

No comments: