public final class RefCountingMemoryTracker<K> extends Object
A tracker that allows calculating the total memory taken by the ref-counted objects it tracks. When first tracked each object has its memory footprint added to a total counter and is tracked until its ref count reaches 0. When the tracked object is eventually removed, its memory footprint is subtracted from the total counter.
Note that due to its intended use (tracking specific memory-occupying object instances) the tracker relies on object identity as opposed to object equality. It's also thread-safe although it does expect that its invariants are generally maintained - e.g. if tracking is initialized for an object that's already being tracked, for example because of a race, an exception will be thrown.
Constructor and Description |
---|
RefCountingMemoryTracker(Function<K,Integer> sizeEstimator,
long maxTrackedMemory,
Consumer<com.google.common.cache.RemovalNotification<K,AtomicInteger>> expirationCallback) |
Modifier and Type | Method and Description |
---|---|
void |
close()
Closing the tracker clears up its internal state.
|
int |
countDown(K memorySized)
Decrements with 1 the ref count of the given ref-counted memory-occupying object.
|
boolean |
initCount(K memorySized,
int refCount)
Starts tracking the given ref-counted memory-occupying object.
|
long |
totalBytes() |
public RefCountingMemoryTracker(Function<K,Integer> sizeEstimator, long maxTrackedMemory, Consumer<com.google.common.cache.RemovalNotification<K,AtomicInteger>> expirationCallback)
sizeEstimator
- A pure function used to estimate the memory footprint of each tracked
object of the given type. Ideally should return 0 for null input, even
though it's not expected to be called with such.maxTrackedMemory
- The maximum number of bytes that all tracked objects can occupy in
total. initCount(Object, int)
attempts that would result in
exceeding that limit will be rejected.expirationCallback
- A callback processing the removal notifications fired whenever a
tracked object is removed from the tracked set due to its ref count
reaching 0.public boolean initCount(K memorySized, int refCount)
memorySized
- The object that is being tracked. Must not be null and must not be tracked
already.refCount
- The initial ref count for the object. Must be positive.true
if the object is successfully added for tracking, false
otherwise.public int countDown(K memorySized)
memorySized
- The object that is being ref-counted down. Must not be null.public void close()
public long totalBytes()