Reference counting¶
Reference counting is a memory management technique used to track the lifecycle of resources, typically buffers or objects, by maintaining a counter that records the number of active references to that resource.^[600-developer__big-data__netty__netty-rotate.md]
Implementation¶
The core mechanism relies on an integer counter (e.g., refCnt) which is initialized to 1 when the resource is created.^[600-developer__big-data__netty__netty-rotate.md]
To ensure thread safety during concurrent access, the counter is usually declared as volatile and manipulated using atomic utilities, such as AtomicIntegerFieldUpdater in Java.^[600-developer__big-data__netty__netty-rotate.md]
Operations¶
Retain (Increment)¶
The lifecycle of a resource is extended through "retain" operations.^[600-developer__big-data__netty__netty-rotate.md]
This process typically involves an infinite loop (Spinlock) that attempts to atomically update the reference count:
1. Read the current count (refCnt).
2. Calculate the new count (nextCnt) by adding the increment.
3. Check for edge cases, such as attempting to "resurrect" an already deallocated resource (where count is 0) or integer overflow.^[600-developer__big-data__netty__netty-rotate.md]
4. Use a Compare-and-swap (CAS) operation (e.g., compareAndSet) to update the count only if it hasn't changed since the read.^[600-developer__big-data__netty__netty-rotate.md]
Release (Decrement)¶
Resources are freed via "release" operations, which decrease the reference count.^[600-developer__big-data__netty__netty-rotate.md]
Similar to retaining, this uses a loop to perform atomic decrements: 1. Read the current count. 2. Verify that the count is not lower than the decrement amount to prevent underflow.^[600-developer__big-data__netty__netty-rotate.md] 3. Use Compare-And-Swap to atomically decrement the counter. 4. If the counter successfully reaches zero (meaning the decrement matches the remaining count), the underlying resource is deallocated.^[600-developer__big-data__netty__netty-rotate.md]
Related Concepts¶
- Atomic note principle
- [[Memory management]]
Sources¶
^[600-developer__big-data__netty__netty-rotate.md]