Subclass instance recorder in Java I've written a relatively small abstract class in Java which keeps track of all instances of it's sublasses. Any class which extends this abstract class will automatically have all its instances stored (via a weak reference) in a Set, which can be retrieved if a subclass ever wants to get references to all it's instances.

Although this class is relatively short and simple, I have never made anything like it and so I want to ensure that I'm not doing something terribly wrong or giving in to any bad practices:

import java.util.*;

public abstract class InstanceRecorder {
    private static Map&lt;Class&lt;? extends InstanceRecorder&gt;, Set&lt;InstanceRecorder&gt;&gt; instances;

    static {
        instances = new HashMap&lt;&gt;();
    }

    {
        instances.putIfAbsent(this.getClass(), Collections.newSetFromMap(new WeakHashMap&lt;&gt;()));
        instances.get(this.getClass()).add(this);
    }

    protected static int countInstances(Class&lt;? extends InstanceRecorder&gt; key) {
        if (instances.containsKey(key))
            return instances.get(key).size();
        return 0;
    }

    @SuppressWarnings("unchecked")
    protected static &lt;T extends InstanceRecorder&gt; Set&lt;T&gt; getInstances(Class&lt;T&gt; key) {
        if (instances.containsKey(key))
            return Collections.unmodifiableSet((Set&lt;T&gt;) instances.get(key));
        return new HashSet&lt;&gt;();
    }
}


As I said above, I've never made a class like this before and so any feedback or insight would be greatly appreciated.
Your code is not thread-safe. You should use ConcurrentHashMap instead of HashMap, if this code is ever run in a multithreaded environment.

In Java 8 there was a terrible performance bug in ConcurrentHashMap.computeIfAbsent, which would lock the whole map even if the key already exists. That bug has been fixed in Java 9. See also this question.