An interviewer asked me that
How can you implement a class Foo, where you will be able to count instances of that class. There are more thread
By doing the exact same thing in reverse.
Since Sun (Oracle) deprecated the unsafe methods of killing threads ( Why are Thread. ... deprecated? ) your thread "exits" by returning from its run()
method.
Simply create a decrementCount()
method in your Foo
class and make sure to call it before returning from run()
in your thread.
Since there's no destructors in Java and, as you point out, finalize()
relies on the GC ... there's not really an automatic way to do this. The only other option I could think of would be to create/use a pool but that's slightly different.