2010-10-06 33 views
0

我在截取屏幕截圖時遇到問題。這是我的測試代碼。可能的Apple JVM bug:java.lang.OutOfMemoryError:Apple.awt.CRobot.getRGBPixels上的Java堆空間(CRobot.java:204)

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); 
      } 
     } 
} 

我的Mac * 小號 *與OS X 10.6.4和Java 1.6.0_20-b02-279-10M3065這兩次迭代後失敗。它似乎在Windows上正常工作。你能重現這種行爲嗎?

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)

回答

3

OutOfMemory表示您需要give the program more memory。這種情況往往會在Mac上更頻繁地發生,因爲現在Java已經是64位了,需要更大的堆。

+0

但爲什麼會發生?由於我沒有在while循環中存儲任何新的引用,GC應該釋放Robot類在內部使用的內存,不應該嗎?當我在循環內部創建一個新的Robot實例時,會發生同樣的情況。 – BlueDog 2010-10-06 10:55:53

+0

東西_somewhere_掛在它上面。在Terminal.app的「jvisualvm」中查看內存分析器。 – 2010-10-06 11:28:23