How much memory should I use in my Java program?

I am making a Java program. This includes creating images up to 9933 * 14043 pixels in size (A0 size and 300 dpi). The image is 24 bits, so it will take about 400 MB of space. In the BufferedImage class, some of them take up more RAM than the actual size of the bitmap, so the image will contain about 600 MB of RAM. When using other data, the application with a maximum size of about 700 mb of bar when rendering a large image. So far I have not had any problems. However, if the end user does not have enough free bar, the JVM will not be able to allocate memory for the bitmap and will throw an OutOfMemoryError.

So what should I do?

I came up with something:

  • Catch an error and cause a request to the user.
  • Wait a while until there is enough memory. If the wait is too long, enter a hint.
  • Write my own bitmap class and write the image in parts using FileOutputStream. The .bmp format is not very complicated. (In fact, I already wrote and optimized most of this.) By rendering a bitmap, the whole image should not remain in RAM. The size of parts can be changed dynamically according to the amount of available memory. However, this is a kind of wheel ingenuity and takes up a significant part of the work. In addition, the part of the image that includes the text needs to be placed in a BufferedImage and then converted to my class (because I don't want to look in the real font format). In any case, if the Java BufferedImage class works in my case, I would not go that way.
+4
1

, - , . , , Runtime.getRuntime().maxMemory(), . , JOptionPane :

long memory = Runtime.getRuntime().maxMemory(); //in bytes
long required = 700 * 1024 * 1024; //700MB, in bytes
if(memory < required) {
    JOptionPane.showMessageDialog(null, "You don't have enough memory. (700MB required)", "Error", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
}

maxMemory() , JVM ( ).

+3

Source: https://habr.com/ru/post/1683620/


All Articles