How to prevent an object from getting garbage collected?

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

    There are 3 ways to prevent an Object from Garbage Collection as following:-

    1. Increase the Heap Size of JVM

      // Xms specifies initial memory to be allocated
      // and Xmx specifies maximum memory can be allocated
      java -Xms1024m -Xmx4096m ClassFile
      
    2. Use a SingleTon Class Object as @Tobias mentioned

      public class MySingletonClass {
           private static MySingletonClass uniqueInstance;
      
           // marking constructor as private
           private MySingletonClass() {
           }
      
           public static synchronized MySingletonClass getInstance() {
              if (uniqueInstance == null) {
                  uniqueInstance = new Singleton();
              }
              return uniqInstance;
          }
      }
      
    3. We can override finalize method. That is last method executed on an object. Hence, it will remain in memory.

      // using finalize method 
      class MyClassNotGc{ 
      
          static MyClassNotGc staticSelfObj; 
      
          pubic void finalize() { 
              // Putting the reference id 
              //Object reference saved. 
              //The object won't be collected by the garbage collector
              staticSelfObj = this; 
          } 
      
      }
      

提交回复
热议问题