How to implement object counter in Java

前端 未结 3 1809
灰色年华
灰色年华 2021-02-20 02:53

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

3条回答
  •  太阳男子
    2021-02-20 03:48

    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.

提交回复
热议问题