How to count the number of objects created for a class?

The following class counts the number of objects present in memory at a given point of time.

ObjectCounter.java

public class ObjectCounter
{

        private static int      objCount        = 0;

        public ObjectCounter()
        {
                objCount++;
        }

        public static void main(String[] args)
        {
                System.out.println(ObjectCounter.objCount++);

                ObjectCounter[] objCnt = new ObjectCounter[20];

                // instantiate all the objects in the ObjectCounter array
                for (int i = 0; i < objCnt.length; i++)
                {
                        objCnt[i] = new ObjectCounter();
                }

                // nullify half the number of objects in the ObjectCounter array
                for (int i = 0; i < objCnt.length / 2; i++)
                {
                        objCnt[i] = null;
                }

                System.gc();
                try
                {
                        Thread.currentThread().sleep(10000);
                }
                catch (InterruptedException e)
                {
                        e.printStackTrace();
                }

                System.out.println("Current number of ObjectCounter objects in memeory -> " + objCount);
        }

        protected void finalize() throws Throwable
        {

                objCount--;
        }
}

Here we have used a static variable, which is incremented in the constructor, whenever an object for the class is created. The counter is decremented before the object is deleted in memory by garbage collector. This operation is being done in the finalize method. This is because the finalize method will be called before the object is destroyed or garbage collected.

Search