The
val weak : 'a ref option -> 'a ref option ref
Constructs a weak reference.
val weakArray : int * 'a ref option -> 'a ref option array
Constructs an array containing weak references.
val weakLock : Thread.Mutex.mutex
and weakSignal : Thread.ConditionVar.conditionVar
A lock and a condition variable that is broadcast when the garbage collector has recovered a token.
val touch : 'a ref -> unit
Uses the reference without changing it, ensuring that it is reachable at that point.
The idea behind weak references is to allow user library code to recover resources when they are no longer in use. This is only relevant for resources, such as file descriptors, that exist outside the Poly/ML memory and need to be recovered.
The garbage-collector recovers space in the heap by identifying cells that are reachable from roots, generally the stacks of threads, and treating everything else as garbage. This can be extended to external resources by associating a token with the resource. While the token is reachable the resource is considered to be in use. Once the token ceases to be reachable the resource can be recovered.
A weak reference is used to detect when the token is no longer accessible.
To make use of this the library code must allocate a normal reference value,
the token, whenever it constructs or links to the external resource and include
the token within the data it returns to the client code. The contents of the
reference are not relevant; it can be a
Provided the client code continues to use the resource and has a reachable
pointer to the token there will be no change to the state. If, though, it discards
the data associated with the resource and hence the pointer to the token the
resource is considered to be released and the library may recover the resource.
If the garbage collector detects that there are no other pointers to the token
except the weak reference it will change the weak reference from
To actually release the external resource the library must check the weak references
or arrays within its own data structures and look for entries that have been
set to
The garbage-collector is only run when necessary and detection of released
resources may happen very infrequently, depending on factors such as the size
of the heap. To force a collection the library can call