Home > OS >  java startup option "-Xmx512M -XX:MaxPerSize=1024M" doesn't work for my jvm
java startup option "-Xmx512M -XX:MaxPerSize=1024M" doesn't work for my jvm

Time:06-12

I'm using oracle jdk1.8 on win10, trying to set max heap size of JVM and see what happens when OOM. Using this code snippet:

package mygroup;
import java.util.ArrayList;
import java.util.List;

public class App 
{
    public static class AUser{
        private String name;
        private String gender;
        private int age;
        public AUser(String n,String g,int a){
            name=n;
            gender=g;
            age=a;
        }
    }

    public static void main( String[] args ) throws Exception
    {
        System.out.println( "App!" );
        List<AUser> users=new ArrayList<AUser>();
        int max=40960000;
        int c=0;
        while(c < max){
              c;
            users.add(new AUser("Me","male",35));
        }
        System.in.read();
    }
}

I compile and run it with

java mygroup/App -Xmx512M -XX:MaxPerSize=1024M

I expect that before it hits "System.in.read()", it should crash and report OOM error for JVM. But nothing happened. Acturally it runs normally, and wait for my key strike.

Then I started java visualVM, connect to "mygroup.App", and executed "heap dump". I could see that this JVM is using around 3.8G memory and totally 40960000 instances of "mygroup.App@AUser" is using 1.47G of memory.

Seems that "-Xmx512M -XX:MaxPerSize=1024M" is not working.

And if I change my program to

        while(true){
            users.add(new AUser("Me","male",35));
        }

to create objects, actually this program will run until there's no more memory of my machine(I have 16G memory!)

So how to make "max heap size" work? Thansk!

CodePudding user response:

The JVM arguments need to go before the class you're running, as Slaw pointed out in a comment above.

Here's a really simple program, all it does it print out whatever string data was sent to the program as input parameters:

import java.util.Arrays;

public class example {
    public static void main(String[] args) {
        System.out.println("arguments: "   Arrays.toString(args));
    }
}

Here are a few runs showing that everything after example.java is simply passed into the program as input arguments:

$ java example.java
arguments: []

$ java example.java one two three
arguments: [one, two, three]

Here's a variation identical to what you posted, with your intended JVM arguments isntead being treated as regular input parameters to the program:

$ java example.java -Xmx512M -XX:MaxPerSize=1024M
arguments: [-Xmx512M, -XX:MaxPerSize=1024M]

So, you'll want to re-order the command input to set JVM parameters instead of sending input parameters to your program.

  • Related