java 'Robot' class memory leak

128 Views Asked by At

I making share screen program.(client)

Sadly, I found out that a memory leak was happening.

To check for memory leaks, I've simplified it to:

import java.awt.*;
import java.awt.image.BufferedImage;

public class Sharescreen {
    public Sharescreen() {
        try {
            Robot robot = new Robot();
            Rectangle winSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

            while (true) {
                BufferedImage image = robot.createScreenCapture(winSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] argv) {
        new Sharescreen();
    }
}

Run :

java -Xms50m -Xmx100m -jar "Share screen.jar"

BUT!! 10 minutes after run the program,

Memory useage: enter image description here

There must be a problem at the 'Robot' class!!!

how can i fix it???

java(jdk) version : openjdk 11.0

1

There are 1 best solutions below

0
On

To me it looks like the problem is with your while loop rather than with Robot. Your code is using the CPU continuously. Adding a Thread.yield() inside the while loop will allow your thread to go to sleep long enough for garbage collecting to take place.