Home > Java > javaTutorial > body text

Detailed explanation of Java's heap memory and stack memory storage mechanism

高洛峰
Release: 2017-01-24 14:47:35
Original
1702 people have browsed it

Heap and Memory Optimization
Today I tested the automatic data sorting function of a project, sorting out tens of thousands of records and pictures in the database. Near the end of the run, java.lang.outOfMemoryError, java heap Regarding space errors, I rarely encountered this kind of memory error when writing programs in the past. Because Java has a garbage collector mechanism, I never paid much attention to it. I searched for some information online today and compiled it based on this.

1. Heap and stack

Heap - created with new, the garbage collector is responsible for recycling

1. When the program starts running, the JVM obtains some memory from the OS, part of which is Heap memory. Heap memory is usually at the bottom of the storage address, arranged upward.

2. The heap is a "runtime" data area, and objects instantiated by classes are allocated space from the heap; 3. Space is allocated on the heap through "new", etc. Established by the instruction, the heap is a dynamically allocated memory size, and the lifetime does not need to be told to the compiler in advance;

4. Unlike C++, Java automatically manages the heap and stack, and the garbage collector can automatically recycle no longer Heap memory used;                  

          5. The disadvantage is that since memory needs to be dynamically allocated at runtime, the memory access speed is slow.

Stack - stores basic types and reference types, fast

1. First-in, last-out data structure, usually used to save parameters and local variables in methods;

2. In Java, all basic types (short, int, long, byte, float, double, boolean, char) and reference type variables are stored on the stack;

3. Survival of data on the stack The space is generally within the current scopes (the area enclosed by {...};

4. The access speed of the stack is faster than the heap, second only to the registers directly located in the CPU;

5. The data in the stack can be shared, and multiple references can point to the same address;

6. The disadvantage is that the data size and lifetime of the stack must be determined, which lacks flexibility.

2. Memory settings

1. Check the memory status of the virtual machine

long maxControl = Runtime.getRuntime().maxMemory();//获取虚拟机可以控制的最大内存数量
long currentUse = Runtime.getRuntime().totalMemory();//获取虚拟机当前已使用的内存数量
Copy after login

By default, the maxControl=66650112B=63.5625M of the java virtual machine;

Nothing If not, currentUse=5177344B=4.9375M measured on my machine;

2. Command to set the memory size

-Xms set initial Java heap size: Set the JVM initialization heap memory size; this value can be set the same as -Xmx to avoid the JVM reallocating memory after each garbage collection is completed -Xmx set maximum Java heap size: Set the maximum JVM heap size. Heap memory size;

-Xmn: Set the young generation size, the entire heap size = young generation size + old generation size + persistent generation size.

-Xss set java thread stack size: Set the JVM thread stack memory size;

  3. Specific operations

     (1) JVM memory settings:

         Open MyEclipse (Eclipse) window-preferences-Java-Installed JREs-Edit-Default VM ARGUMENTS

Enter in VM independent variables: -xmx128m -xms64m -XMN32M -XSS16M

## (2) IDE memory settings:

The myeclipse.ini (or eclipse of eclipse in myEclipse root directory records Modify the configuration under -vmargs in eclipse.ini (under the root directory):

(3) Tomcat memory settings

打开Tomcat根目录下的bin文件夹,编辑catalina.bat

修改为:set JAVA_OPTS= -Xms256m -Xmx512m

三、Java堆中的OutOfMemoryError错误分析

当JVM启动时,使用了-Xms 参数设置的堆内存。当程序继续进行,创建更多对象,JVM开始扩大堆内存以容纳更多对象。JVM也会使用垃圾回收器来回收内存。当快达到-Xmx设置的最大堆内存时,如果没有更多的内存可被分配给新对象的话,JVM就会抛出java.lang.outofmemoryerror,程序就会宕掉。在抛出 OutOfMemoryError之前,JVM会尝试着用垃圾回收器来释放足够的空间,但是发现仍旧没有足够的空间时,就会抛出这个错误。为了解决这个问题,需要清楚程序对象的信息,例如,你创建了哪些对象,哪些对象占用了多少空间等等。可以使用profiler或者堆分析器来处理OutOfMemoryError错误。"java.lang.OutOfMemoryError: Java heap space”表示堆没有足够的空间了,不能继续扩大了。"java.lang.OutOfMemoryError: PermGen space”表示permanent generation已经装满了,你的程序不能再装载类或者再分配一个字符串了。

四、堆和垃圾回收

  我们知道对象创建在堆内存中,垃圾回收这样一个进程,它将已死对象清除出堆空间,并将这些内存再还给堆。为了给垃圾回收器使用,堆主要分成三个区域,分别叫作New Generation,Old Generation或叫Tenured Generation,以及Perm space。New Generation是用来存放新建的对象的空间,在对象新建的时候被使用。如果长时间还使用的话,它们会被垃圾回收器移动到Old Generation(或叫Tenured Generation)。Perm space是JVM存放Meta数据的地方,例如类,方法,字符串池和类级别的详细信息。

五、总结:

  1、Java堆内存是操作系统分配给JVM的内存的一部分。

  2、当我们创建对象时,它们存储在Java堆内存中。

  3、为了便于垃圾回收,Java堆空间分成三个区域,分别叫作New Generation, Old Generation或叫作Tenured Generation,还有Perm Space。

  4、你可以通过用JVM的命令行选项 -Xms, -Xmx, -Xmn来调整Java堆空间的大小。

  5、可以用JConsole或者Runtime.maxMemory(),Runtime.totalMemory(),Runtime.freeMemory()来查看Java中堆内存的大小。

  6、可以使用命令“jmap”来获得heap dump,用“jhat”来分析heap dump。

  7、Java堆空间不同于栈空间,栈空间是用来储存调用栈和局部变量的。

  8、Java垃圾回收器是用来将死掉的对象(不再使用的对象)所占用的内存回收回来,再释放到Java堆空间中。

  9、当遇到java.lang.outOfMemoryError时,不必紧张,有时候仅仅增加堆空间就可以了,但如果经常出现的话,就要看看Java程序中是不是存在内存泄露了。

  10、使用Profiler和Heap dump分析工具来查看Java堆空间,可以查看给每个对象分配了多少内存。

栈存储详解

Java栈存储具有以下几个特点:

一、存在栈中的数据大小和生命周期必须是确定的。

如基本类型的存储:int a = 1; 这种变量存的是字面值,a是一个指向int类型的引用,指向3这个字面值。这些字面值的数据,由于大小可知,生存期可知(这些字面值固定定义在某个程序块里面,程序块退出后,字面值就消失了),出于追求速度的原因,就存在于栈中。

二、存在栈中的数据可以共享。

(1)、基本类型数据存储:

如:

int a = 3;
      int b = 3;
Copy after login

 编译器先处理int a = 3;首先它会在栈中创建一个变量为a的引用,然后查找有没有字面值为3的地址,没找到,就开辟一个存放3这个字面值的地址,然后将a指向3的地址。接着处理int b = 3;在创建完b的引用变量后,由于在栈中已经有3这个字面值,便将b直接指向3的地址。这样,就出现了a与b同时均指向3的情况。

注意:这种字面值的引用与类对象的引用不同。假定两个类对象的引用同时指向一个对象,如果一个对象引用变量修改了这个对象的内部状态,那么另一个对象引用变量也即刻反映出这个变化。相反,通过字面值的引用来修改其值,不会导致另一个指向此字面值的引用的值也跟着改变的情况。如上例,我们定义完a 与b的值后,再令a=4;那么,b不会等于4,还是等于3。在编译器内部,遇到a=4;时,它就会重新搜索栈中是否有4的字面值,如果没有,重新开辟地址存放4的值;如果已经有了,则直接将a指向这个地址。因此a值的改变不会影响到b的值。

(2)、包装类数据存储:

如Integer, Double, String等将相应的基本数据类型包装起来的类。这些类数据全部存在于堆中,Java用new()语句来显示地告诉编译器,在运行时才根据需要动态创建,因此比较灵活,但缺点是要占用更多的时间。

如:以String为例。

String是一个特殊的包装类数据。即可以用String str = new String("abc");的形式来创建,也可以用String str = "abc";的形式来创建。前者是规范的类的创建过程,即在Java中,一切都是对象,而对象是类的实例,全部通过new()的形式来创建。Java 中的有些类,如DateFormat类,可以通过该类的getInstance()方法来返回一个新创建的类,似乎违反了此原则。其实不然。该类运用了单例模式来返回类的实例,只不过这个实例是在该类内部通过new()来创建的,而getInstance()向外部隐藏了此细节。

那为什么在String str = "abc";中,并没有通过new()来创建实例,是不是违反了上述原则?其实没有。

关于String str = "abc"的内部工作。Java内部将此语句转化为以下几个步骤:
  a、先定义一个名为str的对String类的对象引用变量:String str;
  b、在栈中查找有没有存放值为"abc"的地址,如果没有,则开辟一个存放字面值为"abc"的地址,接着创建一个新的String类的对象O,并将O的字符串值指向这个地址,而且在栈中这个地址旁边记下这个引用的对象O。如果已经有了值为"abc"的地址,则查找对象O,并返回O的地址。
c、将str指向对象O的地址。
 值得注意的是,通常String类中字符串值都是直接存值的。但像String str = "abc";这种场合下,其字符串值却是保存了一个指向存在栈中数据的引用(即:String str = "abc";既有栈存储,又有堆存储)。

为了更好地说明这个问题,我们可以通过以下的几个代码进行验证。

String str1 = "abc";
String str2 = "abc";
System.out.println(str1==str2); //true
Copy after login

(只有在两个引用都指向了同一个对象时才返回真值。str1与str2是否都指向了同一个对象)

结果说明,JVM创建了两个引用str1和str2,但只创建了一个对象,而且两个引用都指向了这个对象。

String str1 = "abc";
String str2 = "abc";
str1 = "bcd";
System.out.println(str1 + "," + str2); //bcd, abc
System.out.println(str1==str2); //false
Copy after login

  这就是说,赋值的变化导致了类对象引用的变化,str1指向了另外一个新对象,而str2仍旧指向原来的对象。上例中,当我们将str1的值改为"bcd"时,JVM发现在栈中没有存放该值的地址,便开辟了这个地址,并创建了一个新的对象,其字符串的值指向这个地址。

  事实上,String类被设计成为不可改变(immutable)的类。如果你要改变其值,可以,但JVM在运行时根据新值悄悄创建了一个新对象(没法在原来内存的基础上改变其值),然后将这个对象的地址返回给原来类的引用。这个创建过程虽说是完全自动进行的,但它毕竟占用了更多的时间。在对时间要求比较敏感的环境中,会带有一定的不良影响。

String str1 = "abc";
String str2 = "abc";
str1 = "bcd";
String str3 = str1;
System.out.println(str3); //bcd
String str4 = "bcd";
System.out.println(str1 == str4); //true
Copy after login

  str3这个对象的引用直接指向str1所指向的对象(注意,str3并没有创建新对象)。当str1改完其值后,再创建一个String的引用str4,并指向因str1修改值而创建的新的对象。可以发现,这回str4也没有创建新的对象,从而再次实现栈中数据的共享。

String str1 = new String("abc");
String str2 = "abc";
System.out.println(str1==str2); //false
Copy after login

 创建了两个引用。创建了两个对象。两个引用分别指向不同的两个对象。

String str1 = "abc";
 String str2 = new String("abc");
 System.out.println(str1==str2); //false
Copy after login

 创建了两个引用。创建了两个对象。两个引用分别指向不同的两个对象。

  以上两段代码说明,只要是用new()来新建对象的,都会在堆中创建,而且其字符串是单独存值的,即使与栈中的数据相同,也不会与栈中的数据共享。

 总结:

 (1) When we define a class using a format such as String str = "abc";, we always take it for granted that we have created an object str of the String class. Worry about traps! The object may not have been created! The only thing that is certain is that a reference to the String class is created. As for whether this reference points to a new object, it must be considered according to the context, unless you explicitly create a new object through the new() method. Therefore, a more accurate statement is that we create a reference variable str that points to an object of the String class. This object reference variable points to a String class with a value of "abc". A clear understanding of this is very helpful in eliminating hard-to-find bugs in the program.

 (2) Using String str = "abc"; can improve the running speed of the program to a certain extent, because the JVM will automatically determine whether it is necessary to create a new object based on the actual situation of the data in the stack . For the code of String str = new String("abc");, new objects are always created in the heap, regardless of whether their string values ​​are equal or whether it is necessary to create new objects, thus increasing the burden on the program.


 (3) Due to the immutable nature of the String class (because the value of the wrapper class cannot be modified), when the String variable needs to frequently change its value, you should consider using the StringBuffer class to improve program efficiency.

For more detailed articles on the storage mechanism of Java’s heap memory and stack memory, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!