You will create a static member in the class that will hold the instance counter.
In the constructor will increment this counter.
You just need to know how many were instantiated or need to know how many are instantiated? If you need the second one, you will have to decrease the counter when the object is destroyed or made available.
If it should be decremented in the destruction, it will probably be done in the method finalize()
. If you need to do this when it is no longer used, the decrease should occur in the method dispose()
or something similar that is called whenever it is made available. Or you can use the interface java.lang.AutoCloseable
in the class and the use of the object must be done in such a way as to ensure that it is called, as is the case with the try
with Resources.
Example:
public class teste {
protected static int count = 0;
public teste() {
count++;
}
protected void finalize() throws Throwable {
count--;
}
public static int getInstanceCount() {
return count;
}
}
I put in the Github for future reference.
Obviously this is a simplistic implementation and it will have problems in environment multithreaded.
This operation is not atomic. You may have a thread reading the counter, let’s assume that the counter is worth 1. Then another thread also reads the counter that is still worth 1. The first thread makes increment and it is worth 2. The second thread does the same and it is worth 2. But if it used to be 1, then it had an instance, now two new instances were created by 2 threads simultaneous, totaling 2 instances, but the counter is valid 2. The same occurs in the decrease, counting less than should.
To solve this would have to create some form of locking, ensuring that the operation is atomic.
I don’t know if this is exactly what you’re looking for, so I’ll leave it as a comment: To count the amount of instantiated objects you can use a static variable (e. g.,
static int instantiationCounter
orstatic AtomicInteger instantiationCounter
) and increment the value every time the constructor is called. By defaultfactory
you can do interesting things like store the amount of global instantiations vs the amount of local instantiations (variable in the scope of Factory), etc.– Anthony Accioly