简体   繁体   中英

Best way to declare an array in a long running thread in Java

I have a long running thread that executes the test() method for very long time. What is the best way (in terms of memory & performance) to declare and initialize the data array? What about if data is a one-dimensional array?

Choice #1

public void test() {
    double[][] data;    //declare only

    while (true) {
        //initialize data here every time.
        data = new double[99][9999];

        //do some procesing with data
    }
}

Choice #2

public void test() {

    double[][] data = new double[99][9999];

    while (true) {
        //reset everything in data
        for (double[] row: data)
            Arrays.fill(row, 0.0);

        //do some procesing with data
    }
}

Choice #3 - any suggestions?

As I think choice #2 is better in terms of memory. In the case of choice #1, in every iteration, it gets a new allocation on the heap and the previous allocation is eligible for garbage collection. However, when the previous allocation will be free that depends on the garbage collector (GC). Sometimes, long array allocation may not take place in the young generation. In that case, it will be in the memory for a while (until a full GC). Therefore, memory usages may increase as long as the thread is running. GC only clears the memory when it is needed (particularly from the old generation). Are these observations correct?

999x999999 is roughly 1.000 million doubles, at 8 bytes per double that's 8Gb per allocation. You definitely want to reuse such a large memory chunk instead of throwing it to the garbage collector on each run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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