Java – A reference counting pattern for memory managed languages

cdesign-patternsgarbage-collectionjavareference-counting

Java and .NET have wonderful garbage collectors that manage memory for you, and convenient patterns for quickly releasing external objects (Closeable, IDisposable), but only if they are owned by a single object. In some systems a resource might need to be consumed independently by two components, and only be released when both components release the resource.

In modern C++ you would solve this problem with a shared_ptr, which would deterministically release the resource when all the shared_ptr's are destroyed.

Are there any documented, proven patterns for managing and releasing expensive resources that don't have a single owner in object oriented, non-deterministically garbage collected systems?

Best Answer

In general, you avoid it by having a single owner - even in unmanaged languages.

But the principle is the same for managed languages. Instead of immediately closing the expensive resource on a Close() you decrement a counter (incremented on Open()/Connect()/etc) until you hit 0 at which point the close actually does the close. It'll likely look and act like the Flyweight Pattern.