Java memory area and memory overflow exception

Source: Internet
Author: User

     

One, Java memory area

  The Java Virtual machine divides the memory it manages into several different data regions during the execution of a Java program. These zones have their own purpose, as well as the creation and destruction of time, and some regions exist as the virtual machine process starts, and some regions depend on the user thread's start and end to build and destroy. According to the Java Virtual Machine Specification (JavaSE7 edition), the memory managed by the Java Virtual machine will include the following runtime data regions.

  1. Program counter (thread private)

    Program Counter Register is a small amount of memory space, which can be seen as the line number indicator of the byte code executed by the current thread . In the virtual machine conceptual model, the bytecode interpreter works by changing the value of this counter to select the next byte-code instruction to execute, and the basic functions such as branching, looping, jumping, exception handling, thread recovery, and so on, need to rely on this counter to complete.

Each thread has a separate program counter that does not affect each other and is stored independently.

If the thread is executing a Java method, the counter records the address of the executing virtual machine bytecode instruction;

If the thread is executing a native method, the counter value is empty (undefined).

This memory area is the only area in the Java specification that does not specify any OutOfMemoryError (OOM) conditions

  2.Java virtual machine stack (thread private)

    The VM Stack (Java Virtual machine Stacks) describes the memory model that the Java method executes: Each method creates a stack frame to store information such as local variable tables, operand stacks, dynamic links, method exits, and so on. Each method from the call to the completion of the process, corresponding to a stack frame in the virtual machine stack into the stack and the process.

Commonly referred to in the virtual machine heap memory and stack memory, the stack memory is generally referred to here in the local Variable table section.

A local variable table holds a variety of basic data types, object references (not the object itself, either a pointer to an object or a handle to an object, or other location related to this object, involving the object's access positioning) and the ReturnAddress type.

  3. Local method Stack (thread private)

    The local method stack is very similar to the virtual machine stack (Native), except that the virtual machine stack serves the Java method (bytecode) and the local method stack serves the Native method used by the virtual machine. The Java Virtual Machine specification does not enforce the language, methods, and data structures used by the local method stack. So the virtual machine is free to implement it, and even some virtual machines merge the local method stack and the virtual machine stack directly.

  4.Java heap (thread sharing)

    The Java heap (Java heap) is the largest piece of memory managed by a virtual machine. The only purpose is to store object instances. all object instances and arrays are allocated memory on the heap.

The Java heap is the primary area of garbage collector management. The Java heap can be in a physically discontinuous memory space, as long as it is logically contiguous, similar to disk space. When implemented, it can be either fixed size or extensible, and the current mainstream virtual machines are implemented in a scalable way. An Oom exception is thrown when there is no memory in the heap to complete the instantiation assignment, and the heap cannot be expanded.

  5. Method area (thread sharing)

    The method area is used to store data such as class information, constants, static variables, and code compiled by the immediate compiler that have been loaded by the virtual machine.

The virtual machine specification describes the method area as a logical part of the heap, but with an individual name of Non-heap.

6. Run a constant-rate pool   (thread sharing) 

    The runtime Constant pool is part of the method area.

class file In addition to the class version, fields, methods, interfaces, and other descriptive information, there is a constant pool, for the compilation period generated by the various literal and symbolic references, this part of the class load in the method area of the run-time pool to save.

Java virtual machines have strict rules for the format of each part of the class file. Each byte is used to store which data must conform to the specification to be recognized, loaded and executed by the virtual machine, but for running a constant pool, the Java Virtual Machine specification does not require any details, and different virtual machines can be implemented according to their own requirements. However, in general, in addition to saving the symbolic references described in the class file, the translated direct references are also stored in the run-time-constant pool.

Another important feature of running a constant pool relative to a class file's const pool is its dynamic nature , and the Java language does not require constants to be generated only when compiled, and new constants may be put into the pool during runtime. The Intern () method of the string class is the most exploited.

An oom exception is excluded when the memory can no longer be requested.

second, hotspot virtual machine Object Quest

  The discussion of the object assignment, layout and access process of the hotspot virtual machine in Java heap.

  1. Creation of objects

   Java is an object-oriented language, and it is possible for objects to be created at any time during the execution of a program, and at a linguistic level, creating objects (such as cloning, deserialization) is usually just the new keyword.

Process:

    • Load class: When a virtual opportunity comes to a new instruction, first check whether the parameter of this directive can be positioned in a constant pool to a symbolic reference of a class, and by checking whether the class represented by this symbol has been loaded, parsed, and initialized. If not, the appropriate class loading process is performed. (The details of this section are not discussed here, refer to chapter seventh)
    • allocating memory: after the class is loaded, the virtual machines allocate memory for the new object, and the memory required by the object can be determined after the class is loaded, and allocating space for the object is separated from the Java heap. At this time there are two common methods: (1) Pointer collision: If the heap memory is absolutely regular, already used on one side, not used on the side, there is a split pointer, then only need to move the split pointer to the unused memory of the required fixed size (2) idle list: Java heap memory is not regular, Unused is interleaved with each other, the virtual machine maintains a list of what is already in use, which is unused, and allocates a fixed size to the new object in memory that is never used.

The choice of which method is determined by whether the heap memory is structured or not, and whether it is structured depends on whether the garbage collector in use has a compression collation capability.

It can be obvious that this method of allocating space is not thread-safe, it may be in the assignment of a object before the pointer can be modified, object B uses the original pointer, to solve the problem there are two scenarios:

(1) Synchronizing the actions of the allocated space: in fact, the virtual machine uses CAs with the failed retry method to maintain the atomicity of the update operation (either all done or not done at all).

(2) The memory allocation action is divided into different space according to the thread, that is, each thread allocates a chunk of memory in the Java heap and becomes the local thread allocation buffer Tlab. Which thread allocates memory is allocated on the tlab of that thread, and only when Tlab runs out and assigns a new tlab does it require a synchronous lock.

    • Memory Space initialization: After the memory allocation is over, the virtual machine initializes the allocated memory space to a value of 0 (excluding the object header, which is explained in the next section of the allocated memory space), and if Tlab is used, the work can be done in advance to Tlab allocation, This ensures that an instance field of an object can be used directly in Java without assigning an initial value, which is a value of 0.
    • Object Header settings: Next, the virtual machines make the necessary settings for the object, for example: Which class is the instance? How do I find the metadata information for a class? Hash code? The GC generational age of the object. This information resides in the object header of the object.
    • Initialize: from the virtual machine perspective, a new object has been generated, but from the Java program, this is just beginning, because the memory of the data content is 0 values, after the execution of new, will execute the <init> method, according to the requirements of the programmer to initialize.

  2. Memory layout of objects

is divided into three parts:

(1) Object header

     ① stores the runtime data of the object itself, such as hash code, GC generational age, lock status flag, thread-held lock, biased thread ID, biased timestamp, and so on. The 32-bit virtual machine is 64bit in the 32bit,64-bit virtual machine, officially known as "Mark Word". However, there are too many runtime data required for storage, in fact it has exceeded 32bit or 64bit, but the object header information is an additional storage cost independent of the data defined by the object itself, taking into account the efficiency of the virtual machine mark Word is designed to be a non-fixed data structure that stores as much information as possible in a very small amount of space, and it uses its own storage space based on the state of the object. For example, in a 32-bit hotspot virtual machine, if the object is in an unlocked state, then no information is stored and locked, and the 25bit storage hashcode,4bit storage Gc,2bit storage lock flag bit, 1bit fixed to 0.

The ② type pointer, which is the pointer to the object's class metadata, which the virtual machine uses to determine which class the object is an example of. Not all virtual machine implementations have to retain type pointers on the data (and the object's access is anchored, as explained below). If the object is a Java array, then the object header must also have a piece of data that records the length of the array, because the size of the array cannot be determined from the metadata of the array.

(2) Example data

      The valid information that the object actually stores, as well as the various types of field content defined in the program code, must be recorded, whether it is inherited by the parent class or defined in the subclass. This portion of the storage order is subject to the virtual machine allocation policy parameters (Fieldallocationstyle) and the order in which the fields are defined in the Java source code. The default allocation policy for the hotspot virtual machine is: Longs/doubles, INTs, Shorts/chars, Bytes/booleans, oop (ordinary Object pointers), as can be seen from the policy, Fields of the same width are always assigned together. If this is satisfied, the variables defined in the parent class will appear before the child class. If the Compactfields parameter value is True (the default is True), then the narrower variable within the subclass may also be inserted into the void of the parent class variable.

(3) Align fill

       Not necessarily exist, there is no special meaning, just the role of placeholder. Because the hotspot VM's automatic memory management must require that the object's starting address must be an integer multiple of 8 bytes, in other words, the object's memory size must be an integer multiple of 8 bytes, or, if insufficient, the integer multiples of 8.

  3. Object access and positioning

      That is, the reference in the stack memory accesses the object in the heap memory. There are two main ways of doing this today:

    (1) using a handle: In the Java heap, a block is partitioned as a handle pool, where the handle address of the object is stored, and the handle contains the object instance data pointer (pointing to the heap memory) and the type data pointer (to the method area).

    (2) Direct pointer: The object's address is stored directly in the stack, and the layout of the objects in the heap includes the object sample data and the type data pointer (to the method area).

Advantages of using a handle: The stable handle address stored in the reference, which moves the object when the object is moved (garbage collection is a very common behavior), changes only the instance data pointer of the handle, and the reference itself does not change.

Advantages of direct pointers: fast speed, saving the time overhead of a pointer positioning. Because object access is very frequent, very little more is also a significant execution cost. The hotspot virtual machine is accessed using the second type of object.

    

Third, actual combat: Oom anomaly

The original book describes the way to produce several anomalies and simple code, specific reference to the original book content.

Java memory area and memory overflow exception

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.