To make sure that you have all the instances of your class, I would not allow you to instantiate directly by creating constructors privateand using a method call staticto create and publish an instance, something like:
public class MyClass {
private static final Collection<MyClass> INSTANCES = new ConcurrentLinkedQueue<>();
private MyClass() {}
public static MyClass newInstance() {
MyClass instance = new MyClass();
INSTANCES.add(instance);
return instance;
}
public static void release(MyClass instance) {
INSTANCES.remove(instance);
}
public static void releaseAll(Predicate<MyClass> predicate) {
INSTANCES.stream().filter(predicate).forEach(INSTANCES::remove);
}
public static void apply(Consumer<MyClass> consumer) {
INSTANCES.stream().forEach(consumer);
}
}
Then your code will be:
// Create my instance
MyClass myClass = MyClass.newInstance();
// Execute some code here
...
// Release the instance once the work is over to prevent a memory leak
MyClass.release(myClass);
...
// Execute some code on all instances
// Here it will print all instances
MyClass.apply(System.out::println);
...
// Release all instances that match with a given test
MyClass.releaseAll(myClass -> <Some Test Here>);
source
share