6 ms·
As someone who has never used weak references in either language, what are the common pitfalls in practical usage?
by sapiogram 2y ago
As someone who has never used weak references in either language, what are the common pitfalls in practical usage?
- sethops1 2y agoThe most common is if you create a reference to a field of a struct that is itself weak. The GC will gc the struct and your var can go from non-nil to nil under the hood despite having zero concurrent code (that you wrote). The good news is the vast majority of code using Weak semantics is gratuitous - "clever" code that is actually broken premature optimization, and the fix is to just Don't Do That.
- masklinn 2y agoAFAIK the biggest issue is the nondeterminism ("inconsistency"), especially in languages which have a weaker type system and make upgrading easy (which is the case of both Go and Java) - you need to remember to check the result for nil/null, but the type system won't tell you - if you upgrade twice in a row, you can have both fail, both succeed, or the first one succeed and the second one fail It can also be tricky to use them as building blocks for weak collections, if you want to avoid unbounded growth.