Wednesday, 12 July 2017

Java | What will happen when an infinite loop is called to create the objects in the same Reference?


package com.java.gc;
import java.util.List;
import java.util.ArrayList;

class Finalize extends Thread {
     int[] array;
     private int thread;
     public Finalize(int thread) {
           array = new int [1000000];
           this.thread = thread;
     }

     @Override
     public void run() {
           for (int i = 0; i < array.length; i++) {
                array[i] = i;
           }
     }
    
     @Override
     protected void finalize() throws Throwable {
           System.err.println("finalize " + thread);
     }
}

public class TestFinalize {
     public static void main(String[] args) {
           int counter = 0;
          
           List<Finalize> list = new ArrayList<Finalize>();
          
           while(true) {
                Finalize finalize = new Finalize(counter++);
               
                /** Uncomment the below line will lead to
                 * "java.lang.OutOfMemoryError: Java heap space"
                 *
                 *  However, when the line is commented then all
                 *  finalize object are eligible for garbage collection and finalize
                 *  method will be called for each object while garbage collection.
                 */
                //list.add(finalize);
                finalize.start();
           }
     }
}

Output:
When objects are eligible for garbage collection i.e when list.add(finalize) is commented.
finalize 0
finalize 19
finalize 20
finalize 21
finalize 14
finalize 15
finalize 16
finalize 17
finalize 18
finalize 9

Output:
When objects are eligible for garbage collection i.e when list.add(finalize) is uncommented.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     at com.java.gc.Finalize.<init>(TestFinalize.java:10)
     at com.java.gc.TestFinalize.main(TestFinalize.java:33)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...