std.ref
Description
The ref package provides capabilities related to weak references. A weak reference is a concept relative to a strong reference. For a strong reference, if the reference is not null and the runtime analysis shows that the reachability is true, the GC does not reclaim the reference. However, for a weak reference, the GC may still reclaim the reference even if the reachability is true in some cases.
Weak references are usually used in scenarios such as caches, object pools, thread pools, and event listeners. For example, weak references can be used to cache some large objects for reuse. When the memory is insufficient, the objects referenced by weak references can be automatically reclaimed by the GC to reduce the memory load, whereas the objects referenced by strong references cannot be automatically reclaimed by the GC, which may lead to OOM.
This package provides the WeakRef class, which supports wrapping any object instance into a weak reference instance. If the original object instance has no references other than the weak reference, it may be reclaimed by the GC at a specific time point.
In addition, this package supports two reclamation policies: EAGER and DEFERRED. Under the EAGER reclamation policy, the GC reclaims the objects referenced by weak references as soon as possible. Under the DEFERRED reclamation policy, the GC reclaims the objects referenced by weak references as late as possible, for example, only when the memory is insufficient.
API List
Classes
| Name | Description |
|---|---|
| WeakRef | Provides functionalities related to weak references. If the reference to an object is marked as a weak reference, the GC can reclaim the object according to the specified reclamation policy even if the reference is not null and the object is still reachable. |
| WeakRefBase | Contains no public members or public functions. It cannot be inherited or extended and is used only as a base class for WeakRef. |
Enum
| Name | Description |
|---|---|
| CleanupPolicy | Specifies different reclamation policies, including EAGER and DEFERRED. |