samedi 1 décembre 2018

Java's varying available heap size

I just found out that there are some libraries to compute the shallow size of a java object, so I thought I can also write this in a very simple way. Here is what I tried.

  1. Start the program with some Xmx say A
  2. Create objects of type whose size you want to calculate (say type T) and store them in a list so that GC shouldn't clean them up.
  3. When we hit OOM, let the code handle it and empty the list.
  4. Now check the number of the objects of type T we allocated. Let this be n
  5. Do a binary search to find out the delta inorder to successfully allocate n+1 objects.

Here is the code, I tried out

import java.util.ArrayList;
public class test {
    public static void main(String[] a) {
        ArrayList<Integer> l = new ArrayList<>();
        int i=0;
        try {
            while(true) {
                l.add(new Integer(1));
                i++;
            }
        } catch(Throwable e) {
        } finally {
            l.clear();
            System.out.println(i + "");
        }
    }
}

But I noticed that the number of objects allocated in each run for a same Xmx was varying. Why is this? Is there anything inside JVM randomized?




Aucun commentaire:

Enregistrer un commentaire