简体   繁体   中英

java 'Robot' class memory leak

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: 在此处输入图像描述

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

how can i fix it???

java(jdk) version: openjdk 11.0

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM