Are there any alternative concepts for handling unmanaged resources in garbage collected languages?

118 views Asked by At

Garbage collected object oriented programming languages reclaim unused memory automatically, but all other kinds of resources (i.e. files, sockets...) still require manual release since finalizers cannot be trusted to run in time (or at all).

Therefore such resource objects usually provide some kind of "close"- or "dispose"-method/pattern, which can be problematic for a number of reasons:

  • Dispose has to be called manually which may pose problems in cases when it is not clear when the resource has to be released (similar problem as with manual memory management)
  • The disposable-pattern is somewhat "viral", since each class containing a disposable resource must be made disposable as well in order to guarantee correct resource cleanup
  • An addition of a disposable member to a class, requiring the class to become disposable as well, changes the interface and the usage patterns of the class, thus breaking encapsulation
  • The disposable-pattern creates problems with inheritance, i.e. when a derived class is disposable, while the base class isn't

So, are there any alternative concepts/approaches for properly releasing such resources? Any papers/research in that direction?

1

There are 1 answers

4
Demi On

One approach (in languages that support it) is to manually trigger a garbage collection event to cause finalizers to run. However, some languages (like Java) do not provide a reliable mechanism for doing so.