1

I use Java 8 (In Eclipse) when I got this error:

java.lang.OutOfMemoryError: Java heap space

I've tried the -Xmx command but no use even changing the MetaspaceSize doesn't solve it. This problem occurs when I tried to swap elements of list (it size<= 395).

public void permutation(double[] arr, int pos, ArrayList<double[]> list) {
    if (arr.length - pos == 1)
        list.add(arr.clone());
    else
        for (int i = pos; i < arr.length; i++) {
            swap(arr, pos, i);
            permutation(arr, pos + 1, list);
            swap(arr, pos, i);
        }
}
9

2 Answers 2

2

Changing the amount of heap space you are allocating won't solve the problem.

Your heap is being used up because you are creating an incredible number of objects and looking at what you are trying to achieve, this is likely a bug in your code.

You need to debug your application to determine where all of the objects are being created and why the garbage collector can't clear them up.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of building a List of every possible combination will use a lot of memory and when exploring combinations the number of results can grow exponentially with the number of elements you input.

A simple way around this it to provide a call back to process each combination as it happens. This will leave the amount of work much the same, but the memory consumption drops from O(x^n) to O(1)

public void permutation(double[] arr, int pos, Consumer<double[]> consumer) {
    if (arr.length - pos == 1)
        consumer.accept(arr);
    else
        for (int i = pos; i < arr.length; i++) {
            swap(arr, pos, i);
            permutation(arr, pos + 1, list);
            swap(arr, pos, i);
        }
}

Note: you can create a consumer which adds clones to a List, but you can also print or process the results as you go.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.