Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically increase the memory of Java programs [duplicate]

Possible Duplicate:
Setting JVM heap size at runtime

Is it possible to prevent a program from crashing when it encounters a OutOfMemoryError by increasing the memory allowed to the program?
Can it be done at run time?

Reason for increasing the memory

I was talking a lot of screen shots using java.awt.Robot and after some time my Vector ran out of memory. At 60 BufferedImage it was out.
so 1280 x 800 resolution, 3 byte RGB BufferedImage and 60 images later, the vector was out.
So I guess the memory consumed was
1280 x 800 x 60 x 3 = do the math bytes

like image 436
An SO User Avatar asked Jun 28 '26 10:06

An SO User


1 Answers

Ok well you can't actually increase the heapsize, but you could spawn another process with a new heapsize. Have a play with this:

 public class SpawnAndChangeHeap {
     public static void main(String[] args){  

         //Get the jvm heap size.  
        long heapSize = Runtime.getRuntime().totalMemory();
    JOptionPane.showMessageDialog(null, "" + heapSize );  

    if(args.length > 0 && args[0].equals("-spawn")) {

        try {
            Process proc;
                proc = Runtime.getRuntime().exec("cmd.exe /c java -Xms32m -Xmx128m SpawnAndChangeHeap /n");
        }
        catch(Exception e) {System.out.println("something went wrong");  }
    }
    System.exit(0);


     }  
}
like image 155
Mark Avatar answered Jun 30 '26 00:06

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!