Java notes-java Memory area and GC mechanism

Source: Internet
Author: User

This is the main part of the Java memory area and the GC mechanism of knowledge Summary, the following sections from the network, part from the book, the specific link has forgotten, because this is the time to take notes before learning. Also hope that the original person to forgive!

1 Java garbage collection

java GC(garbage Collection, garbage collection, garbage collector ) mechanism, is one of the main differences between Java and C++/C, as a Java developer, In general, there is no need to specifically write memory recycling and garbage cleanup code, memory leaks and overflow problems, and do not need to be as jittery as C programmers. This is because in the Java Virtual Machine (JVM), there is an automatic memory management and garbage cleanup mechanism. In a nutshell, this mechanism marks the memory in the JVM (Java Virtual machine) and determines which memory needs to be recycled, and automatically reclaims the memory based on a certain recycling strategy, never ending (nerver Stop) Memory space in the JVM to prevent memory leaks and overflow issues.

With regard to the JVM, it is necessary to state that the JDK6, which is currently used by the largest sun company JDK, has been in widespread use since the JDK1.2 of 1999, where the default virtual machines are hotspots. Oracle acquired Sun in 2009, plus the previously acquired EBA company, which has two of the 3 largest virtual machines: JRockit and hotspot. Oracle also demonstrates the intention to consolidate two virtual machines, but currently in the newly released JDK7, the default virtual machine is still a hotspot, so the virtual machines introduced by default in this article are hotspots, and the mechanism is primarily the GC mechanism of the hotspot.

The Java GC mechanism mainly accomplishes 3 things:
(1) Determine which memory needs to be recycled;
(2) determine when to perform GC;
(3) How to perform GC.

After such a long period of development (in fact, before the advent of the Java language, there is the existence of GC mechanisms, such as Lisp language), the Java GC mechanism has been perfected, almost automatically for us to do most of the things. However, if we are engaged in large-size application software development, there have been memory optimization requirements, we must study the Java GC mechanism.

Learning the Java GC mechanism can help us troubleshoot various memory overflow or leak issues in our daily work, address performance bottlenecks, achieve higher concurrency, and write more efficient programs. We will learn the Java GC mechanism from the following four aspects:
(1) How the memory is allocated;
(2) How to ensure that the memory is not mistakenly collected (that is, which memory needs to be recycled);
(3) Under what circumstances the GC and the manner in which the GC is executed;
(4) How to monitor and optimize the GC mechanism.

2 Java Memory Area

To understand the Java GC mechanism, you must first understand the partitioning of memory areas in the JVM. In the Java Runtime Data area, the memory area managed by the JVM is divided into several modules:

which

2.1 Procedure Counter (program Counter Register)

The program counter is a small area of memory that indicates the number of bytes executed by the current thread has been executed to the first line, which can be understood as the line numbers indicator of the current thread. When the bytecode interpreter is working, it removes a statement instruction by changing the value of the counter. Each program counter is used only to record the line number of a thread, so it is thread-private (a thread has a program counter).

If the program executes a Java method, the counter records the virtual machine bytecode instruction address that is executing, and if it is performing a local (native, written by C language) method, the value of the counter is undefined, since the program counter simply records the current instruction address, So there is no memory overflow, so the program counter is the only area in all JVM memory areas where OutOfMemoryError is not defined.

2.2 Virtual machine stack (JVM stack)

Each method of a thread executes at the same time, will create a stack frame (statck frame), the stack frame stored in a local variable table, Operation Stack, dynamic link, method exit, etc., when the method is called, stack frame in the JVM stack, when the method executes, stack frame out of the stack.

The local variable table stores the relevant local variables of the method, including various basic data types, object references, return addresses, and so on. In a local variable table, only long and double types occupy 2 local variable spaces (slots, for 32-bit machines, one Slot is 32 bits), and the others are 1 slots. It is important to note that the local variable table is determined at compile time, and the space required for the method to run is fully deterministic in the stack frame and will not change during the lifetime of the method.
  
Two exceptions are defined in the virtual machine stack, which throws a statckoverflowerror (stack overflow) if the thread call has a stack depth greater than the maximum allowable depth for the virtual machine, but most Java virtual machines allow the size of the virtual machine stack to be dynamically extended (with a small number of fixed lengths). So the thread can always request the stack, knowing that there is not enough memory, at this point, will throw OutOfMemoryError (memory overflow).

Each thread corresponds to a virtual machine stack, so the virtual machine stack is also thread-private.
  

2.3 Local methods Stack (Native method Statck)

The local method stack is the same as the virtual machine stack in terms of function, operating mechanism, exception type, and the only difference is that the virtual machine stack executes the Java method, and the local method stack is used to execute the native method, in many virtual machines (such as the Sun's JDK default hotspot virtual machine), The local method stack is used together with the virtual machine stack.

The local method stack is also thread-private.
  

2.4 Heap District (heap)

The heap area is the most important area to understand the Java GC mechanism, and there is no one. In memory managed by the JVM, the heap area is the largest chunk, and the heap area is the main memory area managed by the Java GC mechanism, which is shared by all threads and created when the virtual machine is started. The heap area exists to store object instances, in principle, all objects are allocated memory on the heap (although in modern technology, it is not so absolute, there are directly allocated on the stack).

In general, according to the Java Virtual Machine specification, heap memory needs to be logically continuous (not physically required), when implemented, can be fixed-size, or extensible, the current mainstream of virtual machines are extensible. If there is still not enough memory allocation and no expansion after the garbage collection is performed, the Outofmemoryerror:java heap space exception will be thrown.
  
There is much more to the heap area, which is described in detail in the next section, "Java Memory allocation mechanism".
  

2.5 Method Area

In the Java Virtual Machine specification, the method area is treated as a logical part of the heap, but in fact, the method area is not a heap (non-heap); In addition, in many people's blogs, the Java GC's generational collection mechanism is divided into 3 generations: The green age, the old age, the permanent generation, these authors defined the method area as " Permanent generation ", this is because, for the previous implementation of the Hotspot Java Virtual machine, the idea of generational collection is extended to the method area, and the method area is designed as a permanent generation. However, most virtual machines other than hotspot do not treat the method area as a permanent generation, and the hotspot itself also plans to cancel the permanent generation. In this article, because the author uses Oracle JDK6.0 primarily, the term permanent is still used.

A method area is a zone shared by each thread that stores the class information that has been loaded by the virtual machine (that is, information that needs to be loaded when the class is loaded, including information such as version, field, method, interface, and so on), final constants, static variables, code that the compiler compiles immediately, and so on.
  
The method area is not physically required to be contiguous, you can choose a fixed size or an extensible size, and the method area has one more limit than the heap: You can choose whether to perform garbage collection. Generally, garbage collection performed on the method area is rare, which is one of the reasons that the method area is known as a permanent generation (HotSpot), but this does not mean that there is no garbage collection on the method area at all, and that garbage collection on it is mainly for the memory reclamation of the constant pool and unloading of the loaded classes.
  
Garbage collection on the method area, the conditions are harsh and very difficult, the effect is not satisfactory, so generally do not do too much to consider, you can stay for further in-depth study later use. The Outofmemoryerror:permgen space exception is defined on the method area and is thrown when there is insufficient memory.

The runtime Constant pool is a part of the method area that stores the literal constants, symbolic references, and direct references that are generated by the compilation period (the symbolic reference is that the encoding is the location of a variable, an interface by a string. The direct reference is the translated address according to the symbol reference, which will be translated in the class link phase); Run a constant pool in addition to storing compile-time constants, you can also store constants generated at runtime (such as The Intern () method of the String class, which acts as a constant pool maintained by string. If the character "ABC" that is called is already in the constant pool, the string address in the pool is returned, otherwise a new constant is added to the pool and the address is returned.
  

2.6 Direct Memory

Direct memory is not a JVM-managed memory, so it can be understood that direct memory is the machine memory outside the JVM. For example, if you have 4G of memory and the JVM occupies 1G, then the rest of 3G is direct memory, and the JDK has a memory allocation method based on channels (channel) and buffers (buffer), and the native libraries implemented by the C language are allocated in direct memory. Referenced by Directbytebuffer stored in the JVM heap. OutOfMemoryError exceptions can also occur because direct memory is limited to the memory of this machine.

This column will continue to update Java knowledge ...

Java notes-java Memory area and GC mechanism

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.