java.lang.Object
net.i2p.util.ObjectCounterUnsafe<K>
Type Parameters:
K - type of objects being counted

public class ObjectCounterUnsafe<K>extends Object
Non-thread-safe counter for tracking occurrences of objects.

This class provides a lightweight alternative to ObjectCounter for single-threaded scenarios. It offers better performance with reduced object churn by using primitive integers instead of AtomicInteger.

Key differences from ObjectCounter:

  • NOT thread-safe - use only in single-threaded contexts
  • Lower memory overhead and better performance
  • Additional add() method for incrementing by arbitrary values
  • sortedObjects() method for retrieving objects by count

Typical use cases include UI components and Sybil attack detection where thread safety is not required.

  • Field Details

  • Constructor Details

    • ObjectCounterUnsafe

      public ObjectCounterUnsafe()
      A counter holding no entries; the backing map starts empty and is filled only by increment(Object) and add(Object, int).
  • Method Details

    • increment

      public int increment(K h)
      Add one.
      Parameters:
      h - the object whose count is raised by one
      Returns:
      count after increment
    • add

      public int add(K h, int val)
      Add a value.
      Parameters:
      h - the object whose count is raised
      val - the number to add, which may be negative
      Returns:
      count after adding
    • count

      public int count(K h)
      Look up the current count for one key.
      Parameters:
      h - the object whose count is looked up
      Returns:
      the count recorded for the key, or 0 if it has never been added
    • objects

      public Set<K> objects()
      The tracked keys, in no particular order.
      Returns:
      set of objects with counts > 0
    • sortedObjects

      public List<K> sortedObjects()
      The tracked keys ordered by descending count, so the most-used come first.
      Returns:
      list of objects reverse sorted by count, highest to lowest
    • clear

      public void clear()
      Start over. Reset the count for all keys to zero.
    • clear

      public void clear(K h)
      Reset the count for this key to zero.
      Parameters:
      h - the object to drop from the map