imageBytes[] does not seem to ever be garbage collected. I've pinpointed a SINGLE LINE that, when commented out, will prevent the memory leak. What could possibly be wrong with this line?
Running this code results in a "OutOfMemoryError: Java heap space" after roughly a minute on my machine. I'm using JRE version 1.5.0_08.
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
// creates images to send to ImageConsumer
public class ImageProducer {
static BufferedImage bufferedImage;
static Robot robo;
static byte[] imageBytes;
public static void main(String args[]) {
try {
robo = new Robot();
} catch(Exception e) {
e.printStackTrace();
}
PipedOutputStream pos = new PipedOutputStream();
new ImageConsumer(pos).start();
bufferedImage = robo.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
try {
ObjectOutputStream oostream = new ObjectOutputStream(pos);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "JPG", baos);
baos.flush();
imageBytes = baos.toByteArray();
while (true) {
ImageIO.write(bufferedImage, "JPG", baos);
baos.flush();
/********************************************************/
// THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
// If you comment the following line out, there will be no
// memory leak. Why? I ask that you help me solve this.
imageBytes = baos.toByteArray();
/********************************************************/
baos.reset();
oostream.writeObject(imageBytes);
pos.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// This thread reads the image data into bImg
class ImageConsumer extends Thread {
BufferedImage bImg;
PipedInputStream pis;
ImageConsumer(PipedOutputStream pos) {
try {
pis = new PipedInputStream(pos);
} catch (IOException e) { e.printStackTrace();}
}
public void run() {
try {
ObjectInputStream oinstream = new ObjectInputStream(pis);
while (true) {
byte[] imageBytes = (byte[])oinstream.readObject();
ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
bImg = ImageIO.read(bais);
}
} catch (Exception e) {e.printStackTrace();}
}
}