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)

BlueDog
  • 966
  • 8
  • 15

1 Answers1

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.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 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. – BlueDog Oct 06 '10 at 10:55
  • Something, _somewhere_ is hanging on to it. Have a look with the memory profiler in "jvisualvm" from Terminal.app. – Thorbjørn Ravn Andersen Oct 06 '10 at 11:28