Обработка: Ошибка нехватки памяти - PullRequest
0 голосов
/ 28 апреля 2011

Я использую Обработка .Вот весь мой набросок:

import guicomponents.*;

PImage backgroundImage;

void setup() {      
  size(911, 715); 
  backgroundImage = loadImage("Floorplan.png");
}
void draw() {
  background(backgroundImage);
  GImageButton[] buttons = {
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10),
    new GImageButton(this, null, "wm.png", 1, 10, 10)
  };
}

(Это просто демонстрация, чтобы проиллюстрировать возникшую у меня проблему.) Если это будет продолжаться достаточно долго, будет сгенерировано OutOfMemoryError:

An OutOfMemoryError means that your code is either using up too much memory
because of a bug (e.g. creating an array that's too large, or unintentionally
loading thousands of images), or that your sketch may need more memory to run.
If your sketch uses a lot of memory (for instance if it loads a lot of data files)
you can increase the memory available to your sketch using the Preferences window.
Exception in thread "Image Fetcher 2" java.lang.OutOfMemoryError: Java heap space
An OutOfMemoryError means that your code is either using up too much memory
because of a bug (e.g. creating an array that's too large, or unintentionally
loading thousands of images), or that your sketch may need more memory to run.
If your sketch uses a lot of memory (for instance if it loads a lot of data files)
you can increase the memory available to your sketch using the Preferences window.
    at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
    at java.awt.image.Raster.createPackedRaster(Raster.java:458)
    at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
    at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:230)
    at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:528)
    at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
    at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:531)
    at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:452)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Exception in thread "Animation Thread" java.lang.OutOfMemoryError: Java heap space
    at processing.core.PImage.<init>(Unknown Source)
    at processing.core.PApplet.loadImageMT(Unknown Source)
    at processing.core.PApplet.loadImage(Unknown Source)
    at processing.core.PApplet.loadImage(Unknown Source)
    at guicomponents.GImageButton.getImages(GImageButton.java:136)
    at guicomponents.GImageButton.<init>(GImageButton.java:100)
    at gimage_demo.draw(gimage_demo.java:35)
    at processing.core.PApplet.handleDraw(Unknown Source)
    at processing.core.PApplet.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:619)

Почему это могло произойти?Разве память не собирает мусор, когда массив выходит из области видимости в конце draw()?

Я столкнулся с этой проблемой, когда пытался заставить кнопку дергаться.Я не мог найти способ изменить его местоположение, поэтому я просто создал новый в новом месте, которое я хотел.Есть ли лучший способ сделать это?

Ответы [ 2 ]

1 голос
/ 28 апреля 2011

Глядя на код (http://code.google.com/p/gui4processing/source/browse/trunk/GUI4Processing/src/guicomponents/G4P.java?r=331) показывает, что все GImageButton экземпляры хранятся в статической HashMap. Я не вижу способа избавиться от них (хотя я не выглядел так уж сложно). Поэтому они выиграли не подходит для сбора мусора.

Я ожидаю, что ответом будет создание кнопок один раз (например, в setup), а затем использование их в draw (если вы не можете найти эквивалент dispose() метода).

1 голос
/ 28 апреля 2011

Почему это может происходить? Разве память не получает мусор, когда массив выходит из области видимости в конце draw ()?

Единственное, что гарантировано, это то, что массив buttons подходит для сборки мусора, когда он выходит из области видимости. Для объектов GImageButton и их членов это зависит от того, какие побочные эффекты имеет конструктор GImageButton.

Убедитесь, что конструктор не «регистрирует» себя в первом аргументе (this в вашем случае), и что кеширование не происходит, или что GImageButton не пропускает, это ссылка this из конструктора и т. д.

...