[英]How much memory should I use in my Java program?
I am making a Java program. 我正在制作一个Java程序。 It involves making a image with size up to 9933 * 14043 pixels (which is A0 size and 300 ppi).
它涉及制作尺寸高达9933 * 14043像素(A0尺寸和300 ppi)的图像。 The image is 24 bit, so it would take up about 400mb of space.
图像为24位,因此占用大约400mb的空间。 The BufferedImage class some how take more RAM than the bitmap's actual size, so the image would comsume about 600 mb of RAM.
BufferedImage类有些如何占用比位图实际大小更多的RAM,因此图像将占用大约600 MB的RAM。 With other data, the app would at max take about 700 mb of ram when rendering the large image.
使用其他数据时,应用程序在渲染大图像时最多会占用大约700 mb的RAM。 I haven't had any problem with it so far.
到目前为止我没有任何问题。 However, if the end user doesn't have enough free ram, the JVM will not be able to allocate the memory for the bitmap and will throw an OutOfMemoryError.
但是,如果最终用户没有足够的可用内存,则JVM将无法为位图分配内存并将抛出OutOfMemoryError。
So what should I do? 所以我该怎么做?
I came up with something: 我想出了一些东西:
I doubt that anyone has less than a gig of ram nowadays. 我怀疑现在任何人都不到一阵公羊。 So you can check if the user has enough memory with
Runtime.getRuntime().maxMemory()
, and if they don't just show an error and close. 因此,您可以检查用户是否有足够的内存与
Runtime.getRuntime().maxMemory()
,如果他们不只是显示错误并关闭。 Here's an example that uses JOptionPane
in the case of an error: 这是一个在出现错误时使用
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()
returns the maximum amount of memory the JVM will attempt to use (in bytes). maxMemory()
返回JVM将尝试使用的最大内存量(以字节为单位)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.