put method

void put(
  1. K key,
  2. V value
)

Associates value with key, replacing any existing association.

If a wrapper is already associated with key:

  • If its value is identical to value, nothing is changed.
  • Otherwise, the previous finalization is detached before attaching the new association.

When key becomes unreachable and is garbage-collected, onFinalize is invoked with the associated value.

Implementation

void put(K key, V value) {
  final previousWrapper = getWrapper(key);

  if (previousWrapper != null) {
    if (identical(previousWrapper.value, value)) {
      // Avoid unnecessary detach/attach when nothing changed.
      return;
    }

    // Cancel pending finalization for the previous association.
    _finalizer.detach(previousWrapper);
  }

  final wrapper = createWrapper(key, value);

  // Attach finalization to the key lifecycle.
  //
  // When [key] is garbage-collected, `_onFinalize(wrapper)` will run.
  // The wrapper itself is used as the detach token, allowing explicit
  // cancellation via `_finalizer.detach(wrapper)`.
  _finalizer.attach(key, wrapper, detach: wrapper);
}