public class InstanceCounter extends Object
WeakReference
system and the WeakHashMap
class in Java.
This will hopefully be useful in debugging memory leaks. The class records
all the objects instantiated (but removes them when the GC deallocates them),
but only reports the counts (allocated, and deallocated -- the difference
between these two counts is the number still in memory). One can use the
debugger to actually LOOK at the objects still in memory. Or one might
extend this class to report on the in-memory objects in more detail.
To use this class, you simple insert the line:
InstanceCounter.add(this);in ALL of its constructors (except ones that call move primitive constructors, of course) of the classes you wish to track. Tracking of all subclasses will automatically occur.
Modifier and Type | Class and Description |
---|---|
(package private) static class |
InstanceCounter.Data<T extends Comparable<T>>
A
WeakReference structure to keep pointers objects added and a
call-count. |
Modifier and Type | Field and Description |
---|---|
private static TreeMap<String,InstanceCounter.Data> |
counts
The "database" of registered objects to keep track of.
|
Modifier | Constructor and Description |
---|---|
private |
InstanceCounter()
This constructor is private to assure that this class is a Singleton (only
one instantiation per process).
|
Modifier and Type | Method and Description |
---|---|
static void |
add(Object o)
Adds an object to InstanceCounter's record.
|
static String |
getReport() |
private static String |
getTheClassName(Object o) |
static void |
report()
Produces a report to standard output.
|
private static TreeMap<String,InstanceCounter.Data> counts
WeakReference
pointers
the objects we're tracking.private InstanceCounter()
public static void add(Object o)
WeakReference
.
For any object to be tracked using InstanceCounter, you should place the line
InstanceCounter.add(this);in ALL of its constructors (except ones that call move primitive constructors, of course).
o
- The object to be tracked.public static void report()
getReport()
public static String getReport()