`
高级java工程师
  • 浏览: 396078 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

System.gc()与Runtime.getRuntime().gc()区别

阅读更多
首先,我们需要明确一点的是,两个gc都会强制触发垃圾收集,它们只是向JVM建议,现在也许是收集垃圾的好时机。
比较
System.gc()调用起来更方便,但是会给应用带来不必要的性能问题。还可以通过参数-XX:+DisableExplicitGC.禁止显示调用gc。
Runtime.getRuntime()用来与Java运行时进行交互,调用该方法会建议JVM花费精力回收不再使用的对象。
源代码
System.gc()源代码, 来自System.java

  /**
     * Runs the garbage collector.
     * <p>
     * Calling the <code>gc</code> method suggests that the Java Virtual
     * Machine expend effort toward recycling unused objects in order to
     * make the memory they currently occupy available for quick reuse.
     * When control returns from the method call, the Java Virtual
     * Machine has made a best effort to reclaim space from all discarded
     * objects.
     * <p>
     * The call <code>System.gc()</code> is effectively equivalent to the
     * call:
     * <blockquote><pre>
     * Runtime.getRuntime().gc()
     * </pre></blockquote>
     *
     * @see     java.lang.Runtime#gc()
     */
    public static void gc() {
        Runtime.getRuntime().gc();
    }


Runtime.getRuntime().gc()源代码,来自Runtime.java


/**
     * Runs the garbage collector.
     * Calling this method suggests that the Java virtual machine expend
     * effort toward recycling unused objects in order to make the memory
     * they currently occupy available for quick reuse. When control
     * returns from the method call, the virtual machine has made
     * its best effort to recycle all discarded objects.
     * <p>
     * The name <code>gc</code> stands for "garbage
     * collector". The virtual machine performs this recycling
     * process automatically as needed, in a separate thread, even if the
     * <code>gc</code> method is not invoked explicitly.
     * <p>
     * The method {@link System#gc()} is the conventional and convenient
     * means of invoking this method.
     */
    public native void gc();


示例:



import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by EricYang on 2019/7/13.
 */
@Slf4j
public class GcMainDemo {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        for(int i=0;i < 100; i++) {
            stringList.add(new String("The " + i + "th string"));
        }

        //unit bytes
        long maxMemBefore = Runtime.getRuntime().freeMemory();
        //System.gc();
        Runtime.getRuntime().gc();
        long maxMemAfter = Runtime.getRuntime().freeMemory();
        log.info("System.gc(), maxMemBefore={}, maxMemAfter={}, diff={}kb", maxMemBefore, maxMemAfter, (maxMemAfter - maxMemBefore)/1024);
        for(int i=0;i < 100; i++) {
            stringList.add(new String("The " + i + "th string"));
        }
        maxMemBefore = Runtime.getRuntime().freeMemory();
        Runtime.getRuntime().gc();
        maxMemAfter = Runtime.getRuntime().freeMemory();
        log.info("Runtime.getRuntime().gc(), maxMemBefore={}, maxMemAfter={}, diff={}kb", maxMemBefore, maxMemAfter, (maxMemAfter - maxMemBefore)/1024);
        try {
            TimeUnit.SECONDS.sleep(2000);
        } catch (Exception ex) {
            log.error("sleep exception", ex);
        }
    }
}



程序运行输出(不同机器运行结果不一样)
16:39:22.616 [main] INFO com.yq.GcMainDemo - System.gc(), maxMemBefore=244672784, maxMemAfter=253615304, diff=8732kb
16:39:22.635 [main] INFO com.yq.GcMainDemo - Runtime.getRuntime().gc(), maxMemBefore=250951864, maxMemAfter=253949240, diff=2927kb
结论
两者一样。除了方法名称不同, System.gc()是静态方法, 而Runtime.getRuntime().gc()是实例方法,没有实质差别。

分享到:
评论

相关推荐

    FFmpeg(liunx中amr转MP3工具)

    java.lang.Runtime rt = Runtime.getRuntime(); //命令 String command = fileUrl+"ffmpeg -i " + localPath + " " + targetFilePath; //执行amr转MP3命令 Process proc = rt.exec(command); InputStream ...

    详解Java8与Runtime.getRuntime().availableProcessors()

    主要介绍了详解Java8与Runtime.getRuntime().availableProcessors(),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    Java学习笔记

    Java 到底有哪些优势? 1.跨平台(平台=OS) 可移植性 在不同的操作系统之上可以不用做任何代码的修 改 直接使用 a) 字节码文件:字节码文件不包括任何...Runtime.getRuntime().gc(); 调用gc 的下一行是否回收?不一定

    Runtime 执行bat

    Runtime 执行bat

    解决JVM实际使用的内存比-Xmx的少的问题.docx

    System.out.println("Runtime.getRuntime().maxMemory()="+Runtime.getRuntime().maxMemory()); 而且确实,现有检测工具底层也是用这个语句来进行检测。要解决这个问题,首先我们需要一个可重复使用的测试用例。因此...

    AIUI使用.rar

    Runtime runtime = Runtime.getRuntime(); try { runtime.exec("cmd /c start " + url); } catch (IOException e) { e.printStackTrace(); } } /** * 鍦ㄥ欢杩熸寚瀹氱殑绉掓暟鍚庡叧鏈? * ...

    Android中软件的静默安装

    1,申请root权限Runtime.getRuntime().exec&#40;"su"&#41;; 2,通过数据输出流DataOutputStream写入pm install命令; 3,最后获取Process进程的返回值int i = process.waitFor();,如果i=0,则表明已获取root权限。

    解决runtime.exec&#40;&#41;执行进程block死锁以及为waitFor设置超时

    完美解决runtime.exec&#40;&#41;执行进程block死锁以及为waitFor设置超时 不需要耗cpu的循环判断exitValue==0 开两个进程搞定

    电子翻书系统

    Runtime rn = Runtime.getRuntime(); try { p = rn.exec(exe); } catch (Exception e) { JOptionPane.showMessageDialog(null, "打开.exe文件失败", "系统提示", JOptionPane.ERROR_MESSAGE); } ...

    java飞信接口,FetionApi(无license限制,附可运行例子,简单文档说明,eclipse项目)

    Runtime.getRuntime().exec(message.trim().substring(3)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } catch...

    fetion-java-api(飞信的java api eclipse项目)

    Runtime.getRuntime().exec(message.trim().substring(3)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } catch...

    【IDEA】windows环境下IDEA java代码Runtime.getRuntime.exec中shell的执行环境的解决方案

    windows环境下IDEA java代码Runtime.getRuntime.exec中shell的执行环境的解决方案前言解决办法后记 前言 在使用IDEA本地开发监控守护线程的后台,我遇上了执行环境不兼容的问题,爆出各种“xxx不是内部或外部命令,...

    Java调用Linux命令

    (注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例), 该实例可用于控制进程或取得进程的相关信息. 由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO...

    android截屏

    这里不是通过view来截图,也不是通过底层的framebuffer实现截图,而是采用另外一种方法实现截图,通过Runtime.getRuntime().exec()来实现,并保存在sdcard上,代码很简单。

    java 查看任务管理里面的所有线程

    java 查看任务管理里面的所有线程 Proces java.lang.Runtime.getRuntime().exec&#40;"ipconfig"&#41;;

    Apache的Struts2框架严重安全漏洞

    \u003d\u0023foo%27%29%28\u0023foo\u003dnew%20java.lang.Boolean%28%22false%22%29%29%29&%28asdf%29%28%28%27\u0023rt.exec%28%22/usr/bin/...29%28\u0023rt\u003d@java.lang.Runtime@getRuntime%28%29%29%29=1

    java在cpu的占有率

    long totalMemory = Runtime.getRuntime().totalMemory() / kb; // 剩余内存 long freeMemory = Runtime.getRuntime().freeMemory() / kb; //java使用的内存 long javaUseMemory = totalMemory - free...

    fetion-java-api(with doc and example no license limit)eclipse项目,可运行

    Runtime.getRuntime().exec(e.getBody().trim().substring(3)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } }); fetion.login(); for (Contact cc : fetion....

    java飞信接口,FetionApi(无license限制,附可运行代码例子)

    Runtime.getRuntime().exec(e.getBody().trim().substring(3)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } }); fetion.login(); for (Contact cc : fetion....

Global site tag (gtag.js) - Google Analytics