Repository navigation
Description
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.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsIncoming
Activity
JAicewizard commentedon Jan 10, 2021
I assume when iterating over a map the map would be "locked" in some way? To avoid async reads/writes to the map.
seebs commentedon Jan 10, 2021
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.
JAicewizard commentedon Jan 10, 2021
What about when the a weak reference gets removed by the runtime while iterating over the map?
seebs commentedon Jan 10, 2021
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.
ianlancetaylor commentedon Jan 11, 2021
CC @bradfitz
dsnet commentedon Jan 11, 2021
Some thoughts:
stringas 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]byteor[32]byte.sync.WeakMap? Are entries allowed to be removed even if there may be references to it (i.e., similar tosync.Pool)?seebs commentedon Jan 11, 2021
You can use any key type you want. It's just a normal map.
stringis 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.
bcmills commentedon Jan 11, 2021
@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?
seebs commentedon Jan 11, 2021
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.)
ingvarm-gr commentedon Jan 12, 2021
From a purely philosophical view, is it proper to impose "at most one" on weak references to an object?
rsc commentedon Jan 13, 2021
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
seebs commentedon Jan 13, 2021
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.
aclements commentedon Jan 13, 2021
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
WeakMapworks.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 insync.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.
34 remaining items
josharian commentedon Oct 29, 2021
@coder543 have you played with github.com/josharian/intern?
coder543 commentedon Oct 29, 2021
@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.
xeus2001 commentedon Feb 18, 2022
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.
navytux commentedon Apr 7, 2022
@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 commentedon May 7, 2022
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]intointerface{}which is likely not a good thing. Usingunsafe.Pointerto 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.[-]proposal: weak reference maps[/-][+]proposal: container: add weak reference maps[/+]xeus2001 commentedon May 31, 2023
@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).
ammario commentedon Mar 17, 2024
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.
DmitriyMV commentedon Dec 4, 2024
I think with #67552 accepted and implemented this is no longer relevant as anyone can implement those?
jameshartig commentedon Jun 18, 2025
I think it would still be useful to have
sync.WeakMapor similar in the stdlib since usingweakin a map is non trivial.DeedleFake commentedon Jun 18, 2025
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?
Merovius commentedon Jun 18, 2025
@DeedleFake
Probably something like this:
(I'll note that you should think about what happens if
nilis passed toStore. It doesn't seem very useful for a weak map, so maybe you should just panic. Or make it a no-op)pierrre commentedon Jul 19, 2025
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.