Skip to content

1.1.5版本之前的内存问题解决方案

yong fan edited this page Dec 17, 2024 · 1 revision

解决思路:

通过获取 PID ,执行shell命令杀死进程。

step 1 通过反射获取pid

 	String version = System.getProperty("java.version");
    double jdkVersion = Double.parseDouble(version.substring(0, 3));
    Class<?> clazz;
    if (jdkVersion <= 1.8) {
        clazz = Class.forName("java.lang.UNIXProcess");
    } else {
        clazz = Class.forName("java.lang.ProcessImpl");
    }
    Field field = clazz.getDeclaredField("pid");
    field.setAccessible(true);
    pid = (Integer) field.get(process);

step 2 通过kill 命令杀死进程

/**
 * kill 掉浏览器进程
 */
public boolean kill(String pid) {
    try {
        if("-1".equals(pid)){
            LOGGER.warn("Chrome process pid is -1,will not use kill cmd");
            return false;
        }
        if(StringUtil.isEmpty(pid) ){
            LOGGER.warn("Chrome process pid is empty,will not use kill cmd");
            return false;
        }
        Process exec;
        String command = "";
        if (Platform.isWindows()) {
            command = "cmd.exe /c taskkill /PID " + pid + " /F /T ";
        } else if (Platform.isLinux() || Platform.isAIX()) {
            command = "kill -9 " + pid;
        }
        LOGGER.info("kill chrome process by pid,command: kill -9 {}", pid);
        exec = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",command});
        return exec.waitFor(Constant.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        LOGGER.error("kill chrome process error ", e);
        return false;
    }
}