Is is possible to keep track of the current number of instances of a class?

JansthcirlU

In .NET, I understand that there is a garbage collector that will manage the memory that's being used during the execution of a program. This means that objects will be cleaned up when they go unused.

I was wondering if I could keep a static counter in a certain class that automatically updates when instances of that class are created or garbage collected. For example, if I create some instances of some CountableInstance class, then they could each have an InstanceIndex that keeps track of their current position based on when they were created.

Such a flow could look like this:

  1. Program starts
  2. CountableInstance ctble0 is created with InstanceIndex == 0
  3. CountableInstance ctble1 is created with InstanceIndex == 1
  4. CountableInstance ctble2 is created with InstanceIndex == 2
  5. CountableInstance ctble1 goes unused and gets garbage collected
  • ctble0's index stays the same
  • ctble2's index becomes 1
  1. Program ends

I'm guessing that keeping track of the number of CountableInstance instances would look like this:

public class CountableInstance
{
    public static int total = 0;
    public CountableInstance()
    {
        InstanceIndex = total;
        total++; // Next instance will have an increased InstanceIndex
    }
    public CountableInstance(...) : this()
    {
        // Constructor logic goes here
    }

    public int InstanceIndex { get; private set; }
}

This takes care of how many instances there are and it also assigns the correct index to each new object. However, this implementation misses the logic that should happen when an instance is garbage collected.

If possible, how could I implement it? Would it also work to keep track of instances of objects that use a particular interface?

Marc Gravell

You can achieve the gist of this as below, but this seems like a bad idea IMO; in particular:

  1. finalizers aren't free (and neither is IDisposable.Dispose())
  2. you can create objects without ever running a constructor (if you try hard enough)

Anyway, code:

public class CountableInstance
{
    static int s_Total, s_Alive;
    public CountableInstance() {
        // need a separate total vs alive so we don't give duplicate
        // InstanceIndex, at least for the first 4 billion objects
        InstanceIndex = Interlocked.Increment(ref s_Total);
        Interlocked.Increment(ref s_Alive);
    }
    ~CountableInstance() {
        Interlocked.Decrement(ref s_Alive);
    }
    public int InstanceIndex { get; }
    public static int Alive => Volatile.Read(ref s_Alive);
    public static int Total => Volatile.Read(ref s_Total);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to keep track of instances of another class in a class?

Class that automatically keeps track of the number of its instances in existence (C++)

Is it possible to limit the number of instances of a class at compile time?

How to keep track of the count of instances of a type?

Using metaclass to keep track of instances in python

Keep track of state in class instance

Do variables in a for loop keep track of the previous number?

How to keep track of number of objects created in java

Selenium how to count and keep track of the number of products

Keep track of number of times android application is opened

How to keep track of instances of python objects in a reliable way?

keep track of parent class from member imageview

Keep track of boolean variable when class is called

How to add class to the next DIV and fade out the current with dynamic number of items - multiple instances

How to Count Number of Instances of a Class

Java unknown number of class instances

Get number of active class instances

Read a file using Stream and keep track of the current index

count number of instances of the class inside the class

Is it possible to return the primitive values of instances of String & Number?

Tryinf to iterate a Map, how to keep track of the number of iterations?

How can I keep track of the number of pivots in Quick Sort?

Java MDB - How to keep track of number of messages processed

How to keep track of number of occurrences between two dependent LinkedLists?

Keep track number of moves of element in array in Shell Sort C++

Multiple instances of Singleton class. Possible?

How can I track the current number of viewers of an item?

Keep track of variables within class when using method multiple times

How does Python keep track of changes in class attributes?