Skip to content

proposal: container: add weak reference maps #43615

Open

Description

@seebs

This is an outgrowth of #32779, and also of https://mdlayher.com/blog/unsafe-string-interning-in-go/ and ensuing discussion of this on Gopher Slack.

Occasionally, it would be desireable to have weak references. Unfortunately, you can't implement these as a user; you need hooks into the runtime to make a safe weak reference implementation, I think. The string interning hack described above probably works but is not complying with the uintptr conversion rules.

In nearly every case where weak references are desireable, it's desireable to be able to look up specific weak references, which suggests something similar to a map data type. It's also desireable to be able to find out whether the weak reference exists, or to be able to request the reference, getting an actual stable non-weak reference back, without a separation between the query and the retrieval.

Conveniently, a map with a pointer key type already provides exactly this behavior. What it doesn't provide is the potential for GC to remove objects.

Thus, my proposal:

cache := make(weak map[string]*Data)

This is equivalent to make(map[string]*Data), except that things which are in the map but not referenced anywhere else may become deleted from the map at any arbitrary time. However, retrieval from the map is guaranteed to either yield a nil (and a false in the ,ok form) or the pointer last stored for that key, and if it yields a non-nil pointer, that pointer is safe to use.

The internal implementation details aren't 100% obvious to me. You could nearly do it with SetFinalizer, except you need a way to ensure that this doesn't clash with any other finalizers used on the item. (For instance, the same value could be present in two weak maps...)

I'm not totally sure about the syntax, but I'm pretty sure that this wouldn't compile now under any possible circumstances, so it doesn't break any existing code.

Why not sync.WeakMap, parallel to sync.Map and/or sync.Pool? Because type safety is nice, and because the ability to use or not use the ", ok" form of retrieval seems desireable. Plain old maps are easier and friendlier to use, and less error-prone.

That said, sync.WeakMap, which would vaguely combine the behaviors of sync.Map and sync.Pool, would be viable too. The main issue this is intended to address is that "would like to keep this if it's convenient and/or if it's being used, but don't need to retain it if there's memory pressure" seems like a common use case.

Activity

  1. added this to the Proposal milestone on Jan 9, 2021
  2. JAicewizard commented on Jan 10, 2021

    @JAicewizard

    I assume when iterating over a map the map would be "locked" in some way? To avoid async reads/writes to the map.

  3. seebs commented on Jan 10, 2021

    @seebs
    ContributorAuthor

    I would assume it'd be the same as any other map. Up to you to ensure that you are not modifying it while the iterator is running.

  4. JAicewizard commented on Jan 10, 2021

    @JAicewizard

    What about when the a weak reference gets removed by the runtime while iterating over the map?

  5. seebs commented on Jan 10, 2021

    @seebs
    ContributorAuthor

    Same thing that would happen with anything else involving pointers in a moving GC: It's up to the runtime to have suitable barriers on or around their accesses.

  6. ianlancetaylor commented on Jan 11, 2021

    @ianlancetaylor
    Contributor
  7. dsnet commented on Jan 11, 2021

    @dsnet
    Member

    Some thoughts:

    • A detriment of using a string as the key is that it probably requires an allocation forming a key to look something up that may not even exist anymore. I see some benefit to an allocation-free key like [16]byte or [32]byte.
    • How complete is a sync.WeakMap? Are entries allowed to be removed even if there may be references to it (i.e., similar to sync.Pool)?
  8. seebs commented on Jan 11, 2021

    @seebs
    ContributorAuthor

    You can use any key type you want. It's just a normal map. string is just an example.

    No, entries can't be removed if there are references to them. If there's references to them, they still exist, and a weak reference should stay valid. The entire point is to have a reliable lookup for these objects if they still exist, without ensuring that they still exist.

  9. bcmills commented on Jan 11, 2021

    @bcmills
    Contributor

    @seebs, how would weak references interact with finalizers (if at all)?

    Specifically: is the weak reference removed from the map before the finalizer is run, or after, or is it forbidden to obtain a weak reference to an object that has a finalizer?

  10. seebs commented on Jan 11, 2021

    @seebs
    ContributorAuthor

    That is a fascinating question. On consideration: If we assume that nothing else ever users finalizers, finalizers might be a credible way to implement this, internally. Runtime can skip the storage for a weak map when marking, and set a finalizer for each item to delete it from the map, roughly. So one solution would be "forbidden to set a finalizer on weak references, or obtain a weak reference to an object with a finalizer". Except... that's horribly brittle, and might result in someone developing a time machine so they can go back to before it was done and add "never use this feature" to Effective Go.

    But this is a really interestingly-difficult philosophical question. It is permissible for a finalizer to actually do a thing that prevents a thing from being collected. So if we remove things from the map first, the object will potentially still exist but we will report it missing (and thus, in most use cases, create a new one). If we run finalizers first, we can have objects in the map which have had their finalizers run, and which can thus end up referenced again post-finalizer. And you can't tell, from the perspective of the caller of the finalizer, whether that finalizer may have stashed the object somewhere so that it won't really be collected.

    And it might be possible to fix this if finalizers had a way to indicate whether or not they were vetoing collection, but that could nonetheless be wrong...

    I think the answer is: Finalizers run after deletion from the map, but if your finalizer preserves the object, it becomes possible that the object exists but the map doesn't refer to it. So don't do that. But not in the sense of "runtime is allowed to explode in a shower of demons", just "yes, so, that previous object is around, and the map doesn't refer to it but might now have a new entry for that key."

    But philosophically, in general, a finalizer is supposed to run "after the object is dead and never referenced again", and it should not do something that would make the object get referenced again, it's just after-the-fact cleanup, and it seems fine for the object to no longer be in the map, and then get cleaned up, even if a new object for its former key ends up getting created.

    (Although if you did, say, "directory named after the key" and the finalizer was "delete the directory" that would be a Bad Idea, and also your own fault, don't do that.)

  11. ingvarm-gr commented on Jan 12, 2021

    @ingvarm-gr

    From a purely philosophical view, is it proper to impose "at most one" on weak references to an object?

  12. rsc commented on Jan 13, 2021

    @rsc
    Contributor

    This is a major language and implementation change on the garbage collector side.
    It is highly unlikely that we are going to add weak references any time soon.
    That's an amazing amount of new complexity.

    /cc @aclements @mknyszek

  13. seebs commented on Jan 13, 2021

    @seebs
    ContributorAuthor

    The "major change" thing is both why it's a hard sell to put it in runtime, and why it's impossible to put it somewhere else.

  14. aclements commented on Jan 13, 2021

    @aclements
    Member

    This is something I've thought about quite a bit in the past. My past thinking has led to a bit of a counter-proposal: don't allow iteration over weak maps. Right now, the garbage collector is invisible in the language semantics (other than finalizers, which are an unfortunate wart at best). The language specification is built on the illusion of infinite memory. If you have a map that allows lookups and not iteration, we maintain that illusion because the GC can delete unreachable keys from that map without any effect on program execution. It remains invisible. An un-iterable map still provides most functionality that people typically want from a weak map, including string interning and carrying side information for objects without forcing them to remain live. There is also exactly how ECMAScript's WeakMap works.

    I would argue that this should at least wait on generics. At that point, we could provide this as a regular type with all the type-safety of the built-in map. I'm not sure where it should live; it's not about synchronization, so it seems odd to put it in sync.

    Implementing the above for pointer keys is actually pretty easy. We'd mark the key storage as non-pointer data, use allocation specials to track the set of weak maps containing an object as a key, and delete keys from those weak maps during sweeping. Disallowing iteration simplifies a lot of questions around races with the GC.

    Implementing it for non-pointer keys is harder, but probably necessary to make it useful. I think the map would have to find the pointers in a key when it's added and attach specials to each of those allocations. During tracing, if the GC reaches any of these objects, it would have to trace across to everything else referenced by that key as well. Object tracing doesn't currently have to look at specials, so I'm not sure how to do this without a performance penalty to every object scanned during GC.

  15. 34 remaining items

  16. josharian commented on Oct 29, 2021

    @josharian
    Contributor

    @coder543 have you played with github.com/josharian/intern?

  17. coder543 commented on Oct 29, 2021

    @coder543

    @josharian thanks, it looks interesting, I think I'll have to give it a closer look soon. Based on a quick review of the (very small!) code, it looks like it won't provide optimal string interning, but it'll probably be a lot better than the nothing that I'm currently using.

  18. xeus2001 commented on Feb 18, 2022

    @xeus2001

    This is a really interesting problem, I implemented my own version of a weak-reference using go 1.18 and will try to do the same for a weak map, but theoretically you could use this already for a weak map. I could as well change the implementation so that I do not "reattach" the finalizer, but let the reference die, but this way it works better, at least with the current GC. In any case, interesting topic.

  19. navytux commented on Apr 7, 2022

    @navytux
    Contributor

    I implemented my own version of a weak-reference using go 1.18

    @xeus2001, for the reference, you might be interested to check how GC can crash when a pointer/interface is recreated from uintptr even if pointed object is known to be still alive and referenced via another regular pointer: #41303 (comment).

  20. MagicalTux commented on May 7, 2022

    @MagicalTux

    I also have my own weakref implementation for go1.18 that seems to be doing fine, based on @xeus2001 's code but with a map object too.

    @navytux I've looked at the #41303 issue and it looks like to be an issue with using direct rematerialization of pointer through transforming uintptr[2] into interface{} which is likely not a good thing. Using unsafe.Pointer to store the object directly seems a better way to do it, and go1.18's generics makes the whole process a lot nicer.

    I've done some load testing and so far I haven't had any crash, even with GOGC=0.

  21. moved this to Incoming in Proposalson Aug 10, 2022
  22. changed the title [-]proposal: weak reference maps[/-] [+]proposal: container: add weak reference maps[/+] on Aug 10, 2022
  23. xeus2001 commented on May 31, 2023

    @xeus2001

    I implemented my own version of a weak-reference using go 1.18

    @xeus2001, for the reference, you might be interested to check how GC can crash when a pointer/interface is recreated from uintptr even if pointed object is known to be still alive and referenced via another regular pointer: #41303 (comment).

    @MagicalTux : I added a comment to the linked issue why I think that the implementation is buggy and what has to be done to fix it (adding a load barrier). However, you could directly try out my version, which uses two atomics where memory ordering is guaranteed (when I get the specs correct).

  24. ammario commented on Mar 17, 2024

    @ammario

    Tried my hand at a weakmap implementation here that uses a single persistent finalizer per non-empty map to automatically evict old entries based on memory pressure. The approach may solve the weak map for memory caching use case but not others.

  25. DmitriyMV commented on Dec 4, 2024

    @DmitriyMV
    Contributor

    I think with #67552 accepted and implemented this is no longer relevant as anyone can implement those?

  26. jameshartig commented on Jun 18, 2025

    @jameshartig
    Contributor

    I think it would still be useful to have sync.WeakMap or similar in the stdlib since using weak in a map is non trivial.

  27. DeedleFake commented on Jun 18, 2025

    @DeedleFake

    It's not too complicated as long as you don't mind things potentially staying in the map after the data has been removed. Or am I missing something subtle in the following (untested) code?

    type WeakMap[K comparable, T any] struct {
    	m sync.Map
    }
    
    func (m *WeakMap[K, T]) Store(k K, p *T) {
    	m.m.Store(k, weak.Make(p))
    	// Maybe something could be done here with runtime.AddCleanup() to
    	// get it to remove itself from the map when it's freed?
    }
    
    func (m *WeakMap[K, T]) Load(k K) *T {
    	p, _ := m.m.Load(k)
    	w, ok := p.(weak.Pointer[T])
    	if !ok {
    		return nil
    	}
    	return w.Value()
    }
  28. Merovius commented on Jun 18, 2025

    @Merovius
    Contributor

    @DeedleFake

    Maybe something could be done here with runtime.AddCleanup() to get it to remove itself from the map when it's freed?

    Probably something like this:

    type WeakMap[K comparable, V any] struct {
    	m sync.Map
    }
    
    type entry[K, V any] struct {
    	k K
    	p weak.Pointer[V]
    	c runtime.Cleanup
    }
    
    func (m *WeakMap[K, V]) Store(k K, p *V) {
    	e := &entry[K, V]{
    		k: k,
    		p: weak.Make(p),
    	}
    	e.c = runtime.AddCleanup(p, func(e *entry[K, V]) {
    		m.m.CompareAndDelete(e.k, e)
    	}, e)
    	old, ok := m.m.Swap(k, e)
    	if ok {
    		old.(*entry[K, V]).c.Stop()
    	}
    }
    
    func (m *WeakMap[K, V]) Load(k K) *V {
    	v, ok := m.m.Load(k)
    	if !ok {
    		return nil
    	}
    	return v.(*entry[K, V]).p.Value()
    }

    (I'll note that you should think about what happens if nil is passed to Store. It doesn't seem very useful for a weak map, so maybe you should just panic. Or make it a no-op)

  29. pierrre commented on Jul 19, 2025

    @pierrre

    For anyone interested, here is a weak map implementation with automatic cleanup:
    https://pkg.go.dev/github.com/pierrre/go-libs/weakutil#Map
    https://github.com/pierrre/go-libs/blob/main/weakutil/map.go
    It supports the same methods as sync.Map.
    I hope the implementation is correct, because it's not trivial to write without locks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    • Status
      Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions