ReferenceCounted.retain is supposed to be called each time we store a new reference to a ReferenceCounted object in the process heap. However, for various reasons, including the fact that manual reference counting is difficult, we sometimes
- Omit calling ReferenceCounted.retain because at the moment of writing the new code we have knowledge non-local to the current method/constructor that allows us to do so. However, this means that reading/changing such code later will require the same knowledge that cannot be acquired by studying the code locally. This is especially confusing in situations when we store two references in heap, but call retain only for one of them.
- Call ReferenceCounted.retain too early in the code, outside of the method/constructor that actually stores a new reference in the heap. Doing so also requires non-local knowledge when reading/changing the code.
As a result, it is very difficult (at least to me, but maybe I am not the only one) to reason about the code that uses reference counting. To improve the matters, we could
- refactor all existing usages of ReferenceCounted such that retain is always called immediately before (in the program order) the write action that stores a new reference in the process heap;
- urge ourselves to follow the approach taken in the aforementioned refactoring.
- is related to
-
JAVA-3978 Introduce self-managing reference counting to AsyncConnection and AsyncConnectionSource
- Backlog