在 OutOfMemoryError (Java) 之前计数对象

Count Objects before OutOfMemoryError (Java)

我是编程初学者,我正在尝试通过下面的 运行 代码与 4 种类型的密钥比较不同类型的 GC。

public class User {

    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("Finalized.");
    }

    public static void showInfo() {
        Runtime runtime = Runtime.getRuntime();
        System.out.println("##### Heap utilization statistics [bytes] #####");
        System.out.println("Used memory: " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes");
        System.out.println("Free memory: " + runtime.freeMemory() + " bytes");
        System.out.println("Total memory: " + (runtime.totalMemory()) + " bytes");
        System.out.println("Max memory: " + (runtime.maxMemory()) + " bytes");
    }

    public static void main(String[] args) {
        int num = 0;
        System.out.println("Start...");
        for (int i = 0; i < 54000; i++) {
            num++;
            new User("Bob", 25);
        }
        System.out.println("Objects created before error: " + num);
        showInfo();
        System.out.println("Finish.");
    }
}

key是(每个代表一种GC类型):

-XX:+UseSerialGC
-XX:+UseParallelOldGC
-XX:+UseParNewGC
-XX:+UseConcMarkSweepGC

我正在使用一个 3mb 的小堆 (-Xmx3mb)。

所以,问题是如何计算在 OutOfMemoryError 之前(在 Java 堆 Space 错误之前)创建的对象数?我的意思是在该代码中创建的对象数量为 54000,但如果我尝试创建更多对象(70000、80000 等),我会遇到错误并且不知道抛出异常的对象数量。有没有一个好的方法来计算,在 OutOfMemoryError 之前我们可以创建多少个对象?

public static void main(String[] args) {
        int num = 0;
        System.out.println("Start...");
        for (int i = 0; i < 54000; i++) {
            try {
                new User("Bob", 25);
                num++;
            } catch(OutOfMemoryError e) {
                break;
            }
        }
        System.out.println("Objects created before error: " + num);
        showInfo();
        System.out.println("Finish.");
    }

您必须捕获异常并仅在成功创建对象时才递增计数器。