Disposing of dismissives

From HaskellWiki
Revision as of 04:31, 9 June 2022 by Atravers (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

An anomaly

Which of the following is "different"?

  • freeSTRef :: STRef s a -> ST s ()
  • closeIORef :: IORef a -> IO ()
  • endMVar :: MVar a -> IO ()
  • discardTVar :: TVar -> STM ()
  • hClose :: Handle -> IO ()
  • finalizeForeignPtr :: ForeignPtr a -> IO ()

...out of all these dismissive definitions, the last two - hClose and finalizeForeignPtr - actually do exist. As for the rest, what service they could provide in the language is much more reliably performed by the implementation! So why not also leave the dismissing of file handles and foreign references to the implementation?


The problem

Resource churn.

Unlike the other types and their values, those of Handle and ForeignPtr allow access to external physical resources which are finite, which would be quickly spent without user intervention via dismissives like hClose and finalizeForeignPtr...here's an idea: adapt the techniques used for those other types and values, so they can also be used with with file handles and foreign references.

The problem is one of liveness, namely the determining of which resources are still accessible from a running program - those which have been discarded can then be reclaimed, along with their resources.


The obvious solution?

This seems the ideal task for the implementation's garbage collector...provided it isn't carrying out a full collection each time a program e.g. uses up its quota of open file handles! That might work for megabyte-sized heaps, but frequently processing multi-gigabyte heaps is an entirely different matter.

The refined solution

The garbage collection process therefore needs to be adapted to the task - using file handles as the example:

1. the list of currently-open file handles are tagged "unused" by the program;
2. the tracing mechanism of the garbage collector operates as usual (during a full collection);
3. any open file handles still tagged "unused" are then closed.

So the tracing mechanism need only examine the heap and other program state in full - the remaining work just involves processing the list of file handles.

Opportunities for improvement

Of course, a direct implementation is only for prototypes, due to the frequent and full traces of all program state. Fortunately, as the technique is based on garbage collection, it can benefit from the extensive prior research, development and experience in this field of study (including hardware-based techniques).



Atravers 05:32, 9 November 2021 (UTC)