Java Virtual machine architecture and common memory overflow exceptions

Source: Internet
Author: User
Tags throwable

Each Java Virtual machine has a classloader subsystem that mounts a type according to a fully qualified name, and each Java Virtual machine has an execution engine that executes the instructions that are contained in the methods of the loaded class.
When a virtual machine runs a program, it needs to get information from the loaded files and organize the information into the runtime data area for easy administration.

data partitioning in the Java runtime
1.Program Counter: The program counter is a small amount of memory space that can be seen as the line number indicator of the current thread's byte code.
The multithreading of a Java Virtual machine is implemented in a way that threads rotate and allocate processor execution time, and at any one time, a processor executes instructions in only one thread. Therefore, in order for the thread to switch back to the correct execution location, each thread needs to have a separate program counter, each thread does not affect each other, independent storage. So the memory area is also called the thread-private memory.
This memory area is the only area in the Java Virtual Machine specification that does not stipulate any oom (outofmemoryerror) conditions.
2. Java Virtual machine stack
Its life cycle is the same as the thread, and each method creates a stack frame to store the local variable table, the operand stack, the dynamic link, and so on. Each method calls to the completion of the process, corresponding to the stack frame into the stack to the process of the stack.
It is often said that Java memory is divided into heap memory and stack memory, so-called stack memory refers to the Java Virtual machine stack, or the virtual machine stack in the local variable table part.
The local variable table holds various base types and object references.
If the thread requests a stack with a depth greater than the virtual machine allows, Stackoverflowerror will be thrown
If the stack of a virtual machine can be dynamically extended, but the extension has an upper limit, the extension cannot request enough memory to throw OutOfMemoryError
3. Local method Stack
The local method stack acts like a virtual machine stack.
The difference is that the Java virtual machine stack executes Java method services for the virtual machine
The local method stack is the native method service used by the virtual machine.
Similar to virtual machine stacks, local method stacks also throw stackoverflowerror and OutOfMemoryError exceptions
4. Java Heap
The Java heap is the largest piece of memory managed by a Java virtual machine and is a thread-shared area.
The Java heap consists of the new generation, the old age and the permanent generation
Cenozoic:
Is the growth, birth, extinction of the region, and finally collected by the garbage collector, the end of life. The Cenozoic is also divided into Eden, from survivor and to survivor. Objects are first allocated in Eden, and when Eden is not stored enough, it is saved to survivor, and if survivor cannot be stored it will move to the old age.
Old Age:
Store objects that are screened from the Cenozoic.

The Java heap can be in a physically disjoint space, as long as it is logically contiguous.
When the heap is implemented, it can be either fixed size or dynamically extensible (-XMX and-XMS). An Oom exception is thrown when the heap cannot be extended.

5. Method Area (permanent generation):
The Java Virtual machine specification describes the method area as a logical part of the heap, but it has another alias that is non-heap (non-heap) and should be distinguished from the Java heap.
  
is a resident memory area that stores the structure information for each class, such as run-time constants
(Runtime Constant Pool), field and method data, constructors, and normal methods of byte-code content, also package
Include some special methods used in class, instance, and interface initialization, that is, the class information that the environment must have, and this area is not reclaimed by the garbage collector. The memory occupied by this area is not released until the JVM is turned off. When the method area fails to meet the memory allocation requirements, Oom is thrown.

Ps:方法区和永久代本质上不等价,但是对HotSpot来说,使用永久代来实现方法区,对于其他虚拟机(BEA JRockit、IBM J9等)是不存在永久代的概念的。

6. Running a constant-rate pool
A run-time constant pool is part of the method area that holds the various literal and symbolic references generated during the compilation period. You can also put new constants into the pool during run time, such as The Intern () method of the String class. An Oom exception is thrown when a constant pool is no longer able to request memory.

7. Direct Memory
Direct memory is a memory area outside of the Java Virtual Machine memory management, Java introduced NIO, introduced a channel-to-buffer-based I/O, you can use the native library to directly allocate out-of-heap memory, and then through the inside of the heap object to operate the memory.
Obviously, the allocation of native direct memory is not limited by the size of the Java heap, which also produces oom exceptions because the native memory size is limited.

    • Examples of common memory overflow exceptions

The

Java heap overflow
Java heap is used to store object instances, creating objects that exceed the heap size to cause heap overflow.

/** * Parameters:-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror *- xms20m Heap Minimum *-xmx20m heap maximum * Set to the same, avoid auto-scaling * *-xx:+heapdumponoutofmemoryerror * allow virtual machines to dump the current memory heap dump snapshot for post-mortem analysis when a memory overflow occurs * * */ public  class  heapoom  { public  static  void  main  (string[] args) {listnew  arraylistwhile  (true ) {List.add (new  heapoom ()); }}}//output: Exception in thread "main" Java.lang.OutOfMemoryError:Java Heap space  

Virtual machine stack and local method stack Overflow

In a single-threaded case, the only exception that can be formed is stackoverflowerror, and we use recursion to cause a stack overflow.

 /** * Reduce stack capacity with-xss128k * / Public  class javavmstacksof {    Private intStacklength =1; Public void Stackleak() {stacklength++;    Stackleak (); } Public Static void Main(string[] args)throwsthrowable {Javavmstacksof Oom =NewJavavmstacksof ();Try{Oom.stackleak (); }Catch(Throwable e) {System.out.println ("Stack length::"+oom.stacklength);ThrowE }    }}//output: Exception in thread "main" Java.lang.StackOverflowError

Zhou Zhiming Teacher in the book said, in the multi-threaded situation, will cause outofmemoryerror anomalies, but I tried, the result is the crash, finally eclipse did not respond, and so on for a long time, forced shutdown.

I put the code on, but the runtime may crash, and everyone is careful.

  Public classjavavmstacksof {Private void Dontstop()    { while(true)        {}    } Public void Stackleakbythread()    { while(true) {Thread th =NewThread (NewRunnable () {@Override Public void Run() {dontstop ();            }            } );        Th.start (); }    } Public Static void Main(string[] args) {Javavmstacksof Oom =NewJavavmstacksof ();    Oom.stackleakbythread (); }}

Method Area Overflow

/* VM args:-xx:permsize=10m-xx:maxpermsize=10m limit the size of the method area * * * Exception in thread "main" Java.lang.OutOfMemor Yerror:permgen space at Java.lang.String.intern (Native Method) * */     Public classRuntimeConstantPoolOOM1 { Public Static void Main(string[] args) {//Use list to keep references, avoid FULLGC recycle constant poollist<string> list =NewArraylist<string> ();inti =0; while(true) {List.add (string.valueof (i++). Intern ()); System. out. println (i); }        }    }//output: Exception in thread "main" Java.lang.OutOfMemoryError:PermGen space

On the book String.intern example, I reprinted from the Internet a very detailed article explanation

Deep analysis of String#intern

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Virtual machine architecture and common memory overflow exceptions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.