How to prevent an object from getting garbage collected?

后端 未结 11 1934
太阳男子
太阳男子 2020-12-02 13:17

How to prevent an object from getting garbage collected?

Are there any approaches by finalize or phantom reference or any other approaches?

I was asked this

11条回答
  •  旧巷少年郎
    2020-12-02 13:56

    This sounds like one of those interview-only-time-you'll-see-it questions. finalize() is run when your object is getting garbage collected, so it'd be pretty perverse to put something in there to prevent collection. Normally you just hold a reference and that's all you need.

    I'm not even sure what would happen if you'd create a new reference for something in the finalizer - since the garbage collector's already decided to collect it would you then end up with a null ref? Seems like a poor idea, in any case. e.g.

    public class Foo {
       static Foo reference;
      ...
      finalize (){ 
         reference = this; 
      }
    }
    

    I doubt this would work, or it might work but be dependant on the GC implenetation, or be "unspecified behavior". Looks evil, though.

提交回复
热议问题