How to implement object counter in Java

前端 未结 3 1733
灰色年华
灰色年华 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:33

    I suppose you could also create a new SoftReference to the newly created instance in the constructor, and collect those in a static list.

    If you want the instance count, you can count the references that are still alive.

    This way, the reference count gets reduced when the garbage collector has done its work.

提交回复
热议问题