1

I'm beginner in java and I tried to make a code which sums two matrixes, but I have the error :

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at Main.main(Main.java:11)

I tried all this commands :

$ java Main
$ java Main -Xmx2048m
$ java Main -Xms1024m
$ java Main -Xms1024m -Xmx2048m
$ java -Xmx2048m Main
$ java -Xms1024m Main
$ java -Xms1024m -Xmx2048m Main

But all give the same error message...

This is the code :

public class Main
{
    public static void main(String[] args)
    {
        final int n = 10000;

        double A[][] = new double[n][n];
        double B[][] = new double[n][n];
        double S[][] = new double[n][n];

        int i,j;

        for (i = 0; i<n; i++)
        {
            for (j = 0; j<n; j++)
            {
                A[i][j] = 1.0d / ((double) i*j);
                B[i][j] = 1.0d / ((double) i*j);
            }
        }

        for (i = 0; i<n; i++)
        {
            for (j = 0; j<n; j++)
            {
                S[i][j] = A[i][j] + B[i][j];
            }
        }
    }
}

So as you can see, this code need ~ 3x8x10000 B = 240 000 B < 2048 MB. My java's version :

$ java -version
openjdk version "11.0.4" 2019-07-16
OpenJDK Runtime Environment (build 11.0.4+11-post-Ubuntu-1ubuntu218.04.3)
OpenJDK 64-Bit Server VM (build 11.0.4+11-post-Ubuntu-1ubuntu218.04.3,     mixed mode, sharing)
3
  • 1
    You are trying to initialize very huge 2-D array. You can try with n =100. Commented Sep 21, 2019 at 15:43
  • 4
    Your code needs ~ 3 x 8 x 10000 x 10000 B Commented Sep 21, 2019 at 15:45
  • 2
    I was able to run your program in my eclipse. But my machine has 16 GB RAM. With out setting -Xmx2048m and -Xms it is working fine Commented Sep 21, 2019 at 16:22

2 Answers 2

1

The flags work, but your math does not check out.

You have 3 arrays, each with 10 000 * 10 000 * 8B values.
For that you need 3 * 10 000 * 10 000 * 8 Bytes... which is 2289 MB.
That is already more than 2048.

To add to that, each of those 3 arrays contains 10 000 references... but the memory overhead of that is minuscule (less than 1MB) compared to the values.

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

1 Comment

Oh yes... I'm stupid --' (and I'im not computer scientist : I'im mathematician !) Thank You !
0

I am able to run your code without any Xms or Xmx setting. My Laptop is having 16 GB Ram.

enter image description here

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.