简体   繁体   English

在OutOfMemoryError(Java)之前计算对象

[英]Count Objects before OutOfMemoryError (Java)

I'm a beginner in programming and I'm trying to compare different types of GC by running code below with 4 types of keys. 我是编程的初学者,我试图通过使用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.");
    }
}

The keys are (each represents one of the GC type): 键是(每个代表一种GC类型):

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

And I'm using a small 3mb heap ( -Xmx3mb ). 我正在使用一个3mb的小堆( -Xmx3mb )。

So, the question is how to count number of created objects before OutOfMemoryError (before Java Heap Space error) ? 那么,问题是如何在OutOfMemoryError之前(Java堆空间错误之前)计算已创建对象的数量? I mean in that code the number of created objects is 54000, but if I'm trying to create more (70000, 80000, etc), I have an error and don't know after what number of object the exception is thrown. 我的意思是在该代码中创建的对象的数量是54000,但如果我正在尝试创建更多(70000,80000等),我有一个错误,并且不知道抛出异常的对象数量。 Is there a good way to count, how many objects we can create before OutOfMemoryError? 有没有一种好的方法来计算,我们可以在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.");
    }

You have to catch the exception and only increment the counter if the object is succefully created. 您必须捕获异常并仅在成功创建对象时递增计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM