lifetimes-0.2.0.0: Flexible manual resource management
Safe HaskellSafe-Inferred
LanguageHaskell2010

Lifetimes.Gc

Description

This module integrates the lifetimes package with GHC's finalizers; this allows you to have the GC run cleanup actions when a resource is garbage collected, rather than managing its lifetime explicitly.

You should think twice before using this; much of the point of this package is to manage resources whose lifetime is *semantically significant*, so in many cases you will want more control over when the resource is released than this module provides. It would be inappropriate to use this if:

  • You need the resource to be cleaned up promptly for semantic reasons (e.g. dropping a network connection).
  • The resource is scarce (e.g. file descriptors), so it is not safe to wait for the garbage collector to get around it.

It is sometimes appropriate however, when time of release is mostly an implementation detail. In particular, this module is fine for use cases where you would want to use a finalizer anyway, and it can be safer: The GHC APIs allow you to attach finalizers to arbitrary values, but doing so is perlious; the compiler and runtime system are free to do many transformations on the code that uses pure values, so it is easy to end up with the finalizer being run sooner than you intended. This module provides a Cell type for finalizable values which is easier to reason about.

Synopsis

Documentation

data Cell a Source #

A cell, containing a value with possible finalizers attached. This differs from Resource in that getting the underlying value cannot fail, since cleanup is controlled by the garbage collector.

Instances

Instances details
Eq (Cell a) Source # 
Instance details

Defined in Lifetimes.Gc

Methods

(==) :: Cell a -> Cell a -> Bool #

(/=) :: Cell a -> Cell a -> Bool #

readCell :: Cell a -> STM a Source #

Get the value from a cell. The value will not be collected until after the all transactions which read it complete.

Note that this is intentionally not in MonadSTM: it is unsafe to use it in IO, since the transaction would be finished as soon as it is read. Instead, in IO you should use acquireCell

acquireCell :: Cell a -> Acquire a Source #

Acquire a reference to the underlying value. This keeps the finalizer from being run before the acquired reference is dropped.

If you need to use the value in IO, you should use this to get a reference to it. If you only need to use it in STM, readCell may be more ergonomic.

moveToGc :: Resource a -> IO (Cell a) Source #

Move a resource to the garbage collector, detaching it from its original lifetime.

newCell :: MonadSTM m => a -> m (Cell a) Source #

Create a new cell, initially with no finalizers.

addFinalizer :: Cell a -> IO () -> IO () Source #

Add a new finalizer to the cell. Cells may have many finalizers attached.