当前位置: 首页 > 面试题库 >

为什么此Java程序占用大量内存?

易星纬
2023-03-14
问题内容

我有一小段代码每隔五分钟拍摄一次我的桌面的屏幕截图。但是,我对它占用的内存量有些困惑-通常它会爬升到200mb
RAM,我敢肯定这是多余的…谁能告诉我a)减少内存占用空间的明智方法或b)它为什么涨 可言

/**
 * Code modified from code given in http://whileonefork.blogspot.co.uk/2011/02/java-multi-monitor-screenshots.html following a SE question at  
 * http://stackoverflow.com/questions/10042086/screen-capture-in-java-not-capturing-whole-screen and then modified by a code review at http://codereview.stackexchange.com/questions/10783/java-screengrab
 */
package com.tmc.personal;

import java.awt.AWTException;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

class ScreenCapture {

    static int minsBetweenScreenshots = 5;

    public static void main(String args[]) {
        int indexOfPicture = 1000;// should be only used for naming file...
        while (true) {
            takeScreenshot("ScreenCapture" + indexOfPicture++);
            try {
                TimeUnit.MINUTES.sleep(minsBetweenScreenshots);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //from http://www.coderanch.com/t/409980/java/java/append-file-timestamp
    private  final static String getDateTime()
    {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("PST"));
        return df.format(new Date());
    }

    public static void takeScreenshot(String filename) {
        Rectangle allScreenBounds = getAllScreenBounds();
        Robot robot;
        try {
            robot = new Robot();
            BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);
            ImageIO.write(screenShot, "jpg", new File(filename + getDateTime()+ ".jpg"));
        } catch (AWTException e) {
            System.err.println("Something went wrong starting the robot");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Something went wrong writing files");
            e.printStackTrace();
        }
    }

    /**
     * Okay so all we have to do here is find the screen with the lowest x, the
     * screen with the lowest y, the screen with the higtest value of X+ width
     * and the screen with the highest value of Y+height
     * 
     * @return A rectangle that covers the all screens that might be nearby...
     */
    private static Rectangle getAllScreenBounds() {
        Rectangle allScreenBounds = new Rectangle();
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] screens = ge.getScreenDevices();

        int farx = 0;
        int fary = 0;
        for (GraphicsDevice screen : screens) {
            Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
            // finding the one corner
            if (allScreenBounds.x > screenBounds.x) {
                allScreenBounds.x = screenBounds.x;
            }
            if (allScreenBounds.y > screenBounds.y) {
                allScreenBounds.y = screenBounds.y;
            }
            // finding the other corner
            if (farx < (screenBounds.x + screenBounds.width)) {
                farx = screenBounds.x + screenBounds.width;
            }
            if (fary < (screenBounds.y + screenBounds.height)) {
                fary = screenBounds.y + screenBounds.height;
            }
            allScreenBounds.width = farx - allScreenBounds.x;
            allScreenBounds.height = fary - allScreenBounds.y;
        }
        return allScreenBounds;
    }
}

问题答案:

其他答案是正确的:Java将使用允许的尽可能多的内存,这时它将进行垃圾回收。要解决此问题,可以在JVM设置中指定较小的最大堆大小。您可以使用-
Xmx设置来执行此操作。例如,如果您认为只需要32MB,则将其运行为:

java -Xmx32M [your main class or jar here]

程序的堆(非堆栈内存)不会占用超过32MB的内存,但是如果一次需要的内存超过该内存的话,它将崩溃(这是您需要剖析的地方)。不过,我在程序中看不到任何明显的泄漏(假设ImageIO不需要任何清理),所以我认为您会没事的。



 类似资料:
  • 嗨,我对java编程还比较陌生。我编写的下面的程序似乎占用了很多内存(大约240 MB,正常吗?-我不这么认为!)请建议一些方法来优化这个程序,以便减少内存存储。 程序-- 代码-

  • 问题内容: 该程序在Java 7中(或在Java 8中带有)可以很好地编译,但是在Java 8中无法编译: 结果: 换句话说,这是Java 7和8之间的 反向 源不兼容。我已经遍历了Java SE 8和Java SE 7 列表之间的不兼容性,但是没有找到任何适合我的问题的东西。 那么,这是一个错误吗? 环境: 问题答案: 感谢您的报告。这看起来像个错误。我会照顾好它,并且一旦我们有更多关于为什么发

  • 在堆上分配内存时,唯一的限制是可用RAM(或虚拟内存)。它产生Gb的内存。 那么,为什么堆栈大小如此有限(大约1 Mb)?什么技术原因阻止您在堆栈上创建真正大的对象? 更新:我的意图可能不清楚,我不想在堆栈上分配巨大的对象,也不需要更大的堆栈。这个问题只是纯粹的好奇心!

  • 对于大学评估,我必须使用一个名为sc的扫描器,具有班级范围,整个课程必须包含在一个班级中。main方法调用方法,该方法使用Scanner和for循环调用两种方法之一以响应用户输入。 这两种方法之一使用扫描仪来计算输入整数的阶乘。执行该方法后, 中的 for 循环将继续。为了避免由于用户输入浮点数而导致的输入不匹配异常,我使用了try/catch。但是,当程序返回到 for 循环时,扫描程序在会导致

  • 问题内容: 我是所有内存管理主题的新手,所以有很多我不了解的事情。 我正在尝试将图像缓存在我的应用程序中,但是我在内存消耗方面遇到了麻烦: 所有的Bitmap Chaching代码都可以从此处复制粘贴:http : //developer.android.com/training/displaying- bitmaps/index.html 我调试了代码,并在Eclipse的DDMS视图中检查了堆

  • 问题内容: 这最终会消耗我所有的可用内存,然后进程被杀死。我曾尝试将标签从更改为“较小”标签,但这并没有什么不同。 我在做什么错/如何处理这个大文件? 我可以轻松地将其切碎并以较小的块进行处理,但这比我想要的还要难看。 问题答案: 当遍历整个文件时,将构建一棵树,并且不会释放任何元素。这样做的好处是元素可以记住其父元素是谁,并且您可以形成引用祖先元素的XPath。缺点是它会消耗大量内存。 为了在解