JVM内存学习

1.freeMemory(),totalMemory(),maxMemory()

java.lang.Runtime类中的 freeMemory(), totalMemory(), maxMemory()这几个方法的反映的都是 java这个进程的内存情况,跟操作系统的内存根本没有关系。

 

maxMemory()这个方法返回的是java虚拟机(这个进程)能构从操作系统那里挖到的最大的内存,以字节为单位,如果在运行java程序的 时 候,没有添加-Xmx参数,那么就是jvm默认的可以使用内存大小,client为64M,server为1G。如果添加了-Xmx参数,将以这个参数后 面的值为准。

 

totalMemory()这个方法返回的是java虚拟机现在已经从操作系统那里挖过来的内存大小,也就是java虚拟机这个进程当时所占用的所 有内存。如果在运行java的时候没有添加-Xms参数,那么,在java程序运行的过程的,内存总是慢慢的从操作系统那里挖的,基本上是用多少挖多少, 直到挖到maxMemory()为止,所以totalMemory()是慢慢增大的。如果用了-Xms参数,程序在启动的时候就会无条件的从操作系统中挖 -Xms后面定义的内存数,然后在这些内存用的差不多的时候,再去挖。

 

freeMemory()是什么呢,刚才讲到如果在运行java的时候没有添加-Xms参数,那么,在java程序运行的过程的,内存总是慢慢的从 操 作系统那里挖的,基本上是用多少挖多少,但是java虚拟机100%的情况下是会稍微多挖一点的,这些挖过来而又没有用上的内存,实际上就是 freeMemory(),所以freeMemory()的值一般情况下都是很小的,但是如果你在运行java程序的时候使用了-Xms,这个时候因为程 序在启动的时候就会无条件的从操作系统中挖-Xms后面定义的内存数,这个时候,挖过来的内存可能大部分没用上,所以这个时候freeMemory()可 能会有些大。

 

2. MaxDirectMemorySize

 

    // A user-settable upper limit on the maximum amount of allocatable direct  
    // buffer memory.  This value may be changed during VM initialization if  
    // "java" is launched with "-XX:MaxDirectMemorySize=<size>".  
    //  
    // The initial value of this field is arbitrary; during JRE initialization  
    // it will be reset to the value specified on the command line, if any,  
    // otherwise to Runtime.getRuntime().maxMemory().  
    //  
    private static long directMemory = 64 * 1024 * 1024;  
      
    // If this method is invoked during VM initialization, it initializes the  
    // maximum amount of allocatable direct buffer memory (in bytes) from the  
    // system property sun.nio.MaxDirectMemorySize.  The system property will  
    // be removed when it is accessed.  
    //  
    // If this method is invoked after the VM is booted, it returns the  
    // maximum amount of allocatable direct buffer memory.  
    //  
    public static long maxDirectMemory() {  
        if (booted)  
            return directMemory;  
      
        Properties p = System.getProperties();  
        String s = (String)p.remove("sun.nio.MaxDirectMemorySize");  
        System.setProperties(p);  
      
        if (s != null) {  
            if (s.equals("-1")) {  
                // -XX:MaxDirectMemorySize not given, take default  
                directMemory = Runtime.getRuntime().maxMemory();  
            } else {  
                long l = Long.parseLong(s);  
                if (l > -1)  
                    directMemory = l;  
            }  
        }  
      
        return directMemory;  
    }  

 

MaxDirectMemorySize没显式配置的时候,NIO direct memory可申请的空间的上限就是-Xmx减去一个survivor space的预留大小

MaxDirectMemorySize显示配置时,NIO direct memory可申请的空间的上限就是该值。

你可能感兴趣的:(jvm内存)