How to prevent an object from getting garbage collected?

后端 未结 11 1955
太阳男子
太阳男子 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:48

    I wonder if what they're going for is the pattern with resource pools (e.g. for network/db connections, or threads) where you use finalize to return a resource to the pool so that the actual object holding the resource isn't GC'ed.

    Stupid example, in Java-like pseudocode and missing any kind of synchronization:

    class SlowResourceInternal {
       private final SlowResourcePool parent;
       
    
       returnToPool() {
           parent.add(this);
       }
    }
    
    class SlowResourceHolder {
        private final SlowResourceInternal impl;
    
        
    
        finalize() {
            if (impl != null) impl.returnToPool();
        }
    }
    

提交回复
热议问题