0

I'm having issues when I take screenshots. This is my test code.

import java.awt.Robot;
import java.awt.AWTException;
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Dimension;

public class Test {
        public static void main(String[] args) throws AWTException {
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            int[] pixels = new int[(int) (screenSize.getWidth() * screenSize.getHeight()) * 3];
            Robot robot = new Robot();
            int i = 0;

            while (true) {
                robot.createScreenCapture(new Rectangle(screenSize))
                     .getRaster().getPixels(0, 0, (int) screenSize.getWidth(), (int) screenSize.getHeight(), pixels);
                System.out.println(++i);
            }
        }
}

On my Mac*s* with OS X 10.6.4 and Java 1.6.0_20-b02-279-10M3065 it fails after two iterations. It seems to work fine on Windows. Can you reproduce this behaviour?

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at apple.awt.CRobot.getRGBPixels(CRobot.java:204) at java.awt.Robot.createScreenCapture(Robot.java:329) at Test.main(Test.java:16)

1 Answer 1

3

OutOfMemory means you need to give the program more memory. This tends to happen on Macs more often these days, since Java is 64bit there now, and needs a bigger heap.

Sign up to request clarification or add additional context in comments.

2 Comments

But why does it happen? Since I'm not storing any new references in the while loop, the GC should free the memory the Robot class uses internally, shouldn't it? When I create a new Robot instance inside the loop the same happens.
Something, somewhere is hanging on to it. Have a look with the memory profiler in "jvisualvm" from Terminal.app.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.