Class RefCountingMemoryTracker<K>

java.lang.Object
io.confluent.kafka.replication.push.buffer.RefCountingMemoryTracker<K>

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 requested for an object that's already being tracked, for example because of a race, an exception will be thrown.

  • Constructor Details

    • RefCountingMemoryTracker

      public RefCountingMemoryTracker(Function<K,Integer> sizeEstimator, long maxTrackedMemory, Consumer<com.google.common.cache.RemovalNotification<K, AtomicInteger>> expirationCallback)
      Parameters:
      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.
  • Method Details

    • initCount

      public boolean initCount(K memorySized, int refCount)
      Starts tracking the given ref-counted memory-occupying object.
      Parameters:
      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.
      Returns:
      true if the object is successfully added for tracking, false otherwise.
    • countDown

      public int countDown(K memorySized)
      Decrements with 1 the ref count of the given ref-counted memory-occupying object.
      Parameters:
      memorySized - The object that is being ref-counted down. Must not be null.
      Returns:
      The resulting ref count after the decrement. If the object was not being tracked, 0 will be returned, as if the object has been untracked successfully.
    • close

      public void close()
      Closing the tracker clears up its internal state. Once closed, the tracker cannot be reused.
    • totalBytes

      public long totalBytes()