When would the garbage collector erase an instance of an object that uses Singleton pattern?

后端 未结 4 1459
夕颜
夕颜 2020-12-01 05:14

When would the garbage collector erase an instance of an object that uses Singleton pattern?

Does an object hang around any longer than a regular object?

How

4条回答
  •  醉梦人生
    2020-12-01 05:46

    There's a static reference to a singleton, so it won't be eligible for garbage collection until the classloader is eligible for garbage collection.

    You can't force any object to be garbage collected; you can request that the garbage collector runs with System.gc() but it's only a request.

    If you really want to make a "singleton" eligible for garbage collection, you'd probably want to have a method to set the static variable to null (and hope that nothing else had taken a copy of the reference). Obviously the next time anyone asked for an instance, it would need to be recreated... at which point it's not really a singleton, of course.

提交回复
热议问题