JVM learning and memory problems are summarized --java area and memory overflow exception

  • java virtual machine memory into which areas?
    According Java SE7 version of the Java Virtual Machine Specification, including virtual machine memory management data area 5 runtime:
  1. Program Counter
  2. VM stack
  3. Native method stacks
  4. Methods district
  5. stack
  • Each part of the run-time data area of effect ?

    • 程序计数器

      A row number designator thread bytecode executed.

      Bytecode interpreter by changing the value of the counter to select a next instruction to be executed, then the branch, looping, branching, exception handling, recovery need to rely on a counter thread to complete. The Java Virtual Machine is among multiple threads to perform tasks by switching threads for CPU time slice, when a thread to reacquire CPU time slice when you need to restore the previous position and status of tasks performed, then each thread has a independent program counter is responsible for recording the address of the virtual machine bytecode instructions being executed.

  • Java虚拟机栈

    VM stack for the Java virtual machine to perform the method of service each method will be executed at the same time create a stack frame used to store information local variable table, the operand stack, dynamic linking, method exports. In which a thread, each of the call and ends execution of the method on a stack frame corresponds to push the stack in a virtual machine process stack.

  • 本地方法栈

    Native method stacks using a virtual machine to Native service method, similar to the role played by the virtual machine stack.

  • Java堆

    Java heap is usually the biggest piece of the Java virtual machine managed by the memory of them to create the virtual machine starts, all threads share, which may be at discrete physical space, but logically it must be continuous, the only role is used to store object instances, i.e. a common object instances and arrays are allocated on the heap space.

  • Methods district

    A method for storing class information area of ​​the virtual machine has been loaded, constants, variables and the static time compiler to compile the code and other data. It and the Java heap, as each thread is a shared memory area and does not require contiguous memory and can choose a fixed or scalable space, similar to the heap.

  • HotSpot virtual machine how objects are created?

    When the virtual opportunity to a new instruction, the first thing would be to check the method area constant pool can not be located to sign a class corresponding references, then check this symbolic references corresponding to whether or not the class is loaded and initialized to resolve, if not first make the appropriate class loading process, and then by the virtual machine to allocate memory for the newborn objects, and the size of this space is in the process of class loading has been finalized, then directly assigned directly corresponding space in the heap. But the heap of spare space may be structured may also be fragmented, distribution system under the two cases are different: if it is regular "pointer collision" approach can be used to allocate memory, if it is fragmented a "free list way of distribution."

    After the virtual machine memory allocated for the object end, will be assigned to the memory initialized to zero value, this step ensures that the instance fields of an object without initial value can also be accessed directly in java code.

    And the need to set up a virtual machine needs to be an object of some important information on the target object head among the information which is the object is an instance of the class, how to find information such as metadata and hash code value and generational GC Age and so on.

    So the above steps, the virtual machine in a new object has been created.

    In general, however, after the execution of new instructions will be followed by <init> method is initialized according to the programmer's idea, such an object on the java program to create a truly level out.

  • An object consists of several parts?

    In HotSpot VM as an example, the object is stored in memory layout can be divided into three regions:

    • 对象头

      Of two parts of the main memory object header, the object itself is the first runtime data, such as hash code, the GC generational age thread holds the lock status flag and the content of the lock; other part is a pointer type, it is the object point pointer class metadata, the virtual object through a pointer to determine which object is an instance of this class belong.

    • 实例数据

      Examples of valid data is actually stored in the object information, including the contents of the program code are stored in the various fields of the parent class in this.

    • 对齐填充

      This part will not be bound to exist, that is, from a placeholder effect, for example due to an automatic memory management system of claim HotSpot VM object size must be an integer multiple of 8 bytes, then the instance data portion is not aligned when it alignment padding required to fill the whole.

  • How to access the object is located?

    java program operation of the heap data objects referenced on the stack, the specific position location reference objects in a heap access the virtual machine is currently in the mainstream is mainly achieved by two ways: using the direct pointer or handle.

  • oom abnormalities may be sent in which area in what circumstances?

    Heap, stack virtual machine with native method stacks, and wherein the method area the runtime constant pool, the unit direct memory.

  • How to determine heap objects Can be recycled?

    No longer is any way to use an object, that is "death", it can be recovered.

    To determine if the object is "alive" or death by reference counting algorithm and reachability analysis algorithm .

    • 引用计数算法

      Add a reference to an object counter, the referenced object when the counter value is incremented by 1 when the reference value of the failure counter is decremented, the counter for the object 0 is no longer being used, which can be recycled the objects. But the mainstream virtual machine is rarely used during memory management algorithm, although this method is very efficient judgment, but it is difficult to solve the problem of mutual circulation between object references.

    • 可达性分析算法

      By a series of objects called "GC Roots" as a starting point, the starting node down search , called search path traversed chain of references, when an object to GC Roots chain no time reference, i.e. the when GC Roots objects unreachable, the object is not available, can be recovered.

      In the Java language as GC Roots objects include objects in the virtual machine stack referenced object method area referenced in static property, object method constant reference area and the local Native methods object method reference stack .

      • But even in the determination of reachability analysis algorithm unreachable objects also have the opportunity to escape the recovery of the real announced the death of an object at least twice to go through the labeling process, the first is the result of reachability analysis is determined that no phase with GC Root reference connection chain, and screening for a marker, screening is necessary that execution finalize () method, and when the object does not cover the finalize () method , or has been executed are considered unnecessary to perform.

        Because finalize any object () method will only be automatically called once the object either the final self-help among the only time finalize () method call, it can 重新与引用链上任何一个对象关联的方式进行一次自救, but in this process is the object of this GC marking the second time, this time removed the collection "is about to be recycled"; and if the object is facing next is recovered, finalize () method has been executed, and will not execute again, the object nor way out of recycled fate.

  • Common garbage collection algorithm What?

    • 标记-清除算法

      First of all marked objects need to be recovered, after completion of all objects are marked marked uniform recycling. But this way mark and clear two-step efficiency is not high, and will leave a discontinuity of memory fragmentation, when then they have to allocate space for the larger object because no way could find enough contiguous memory and had earlier triggered a garbage collection action.

  • 复制算法

    The available memory capacity is divided into two identical, only one of them each time. In front of a block of memory runs out, the copy will also survived an object onto another piece of memory, and then finished already used this one-time clean up memory space. In this way do not have to worry about the allocation of memory chips, simple and efficient, simply move the pointer to the top of the heap objects that can allocate space, but each time the memory can be used only half of the original, the price is relatively high. But when the higher survival rate of the object will be carried out more copy operations, efficiency will be lower, but due to the large object declared the new generation cycle is not long, so copying garbage collection algorithm for the new generation is very appropriate.

  • 标记-整理算法

    - Mark sorting algorithm to the labeling process - cleaning algorithm is the same, the subsequent steps are all live objects are moved to an end, and then clean out the direct memory boundary side. Mark - sorting algorithm to solve the mark - not a problem sorting algorithm contiguous memory, compared to replication algorithms at a high survival rate target situation have higher collection efficiency, suitable for old age characteristics of its garbage collection.

  • 分代收集算法

    The idea of ​​generational collection algorithm is divided according to different objects to survive periods of different memory, the java heap is generally divided into the old and the new generation's, to take the most appropriate garbage collection algorithms to the characteristics of each era, the new generation of live objects on the use of low copy algorithm, so long as the pay copying costs less to complete garbage collection, but it may take years for the old mark - cleaning algorithm or mark - collation algorithm for recycling.

  • What types of references why so many sub-types ?

    Referenced in the definition of very traditional Java JDK1.2 before: If the value of reference type is stored on behalf of another piece of memory starting address, this memory is said to represent a reference. So for the previously defined reference JDK1.2 it is quite narrow, with one object only and may not be two states and, when the state of the object to be a little more complex description inside the virtual machine can not do anything. After JDK1.2, Java concept was expanded references, references into a strong references, soft references, weak references, phantom references .

    • Strong references

      Refers to strong reference prevalent in the program code, similar to "Object obj = new Object ()" of this type reference may be accessed by the corresponding reference object, as long as there are still strong reference, the garbage collector will not fall recovered referenced object.

    • Soft references

      For objects associated soft references, before memory overflow exception system is imminent, these objects will be included within the scope of recovery, a second recovery, or not enough memory if this recovery, the system will throw memory overflow exception. Code can be realized in this manner:

      Object obj=new Object();
      SoftReference<Object> softReference=new SoftReference<>(obj);
      obj=null;
      System.out.println(softReference.get());

      softReference soft obj is a reference, and when the object is marked as reference obj objects need to be recovered, the softReference.get () return null, the main function of the soft reference implement caching user when sufficient memory, they can be directly Getting Object soft references, and when the memory is not enough time, it will clear out the soft reference object, if you still do not have enough memory space will throw an overflow exception.

    • Weak references

      Weak references intensity weaker statement cycle is only a weak reference object is more short-lived, weak reference object is associated only to survive until the next garbage collection, garbage collection when carried out, regardless of whether sufficient memory, are softer than the reference the recovery is weak reference object is only associated. WeakReference provides classes to implement a weak reference.

    • False quote

      Virtual reference is a reference to the weakest relationship, there is a virtual reference will not have an impact on the life cycle of an object, the object instance could not get through it, just to get set up phantom reference object is recovered when a collector system notification. Class can be used to implement virtual PhantomReference reference.

    Soft, weak, references, virtual references and references queues used in combination, if the object referenced is to be recovered garbage collector when will the add a reference to a reference to the column which then after the program by Analyzing reference queue which is enough there is a reference to the object to determine whether the object will be recycled, it can take some measures before the object is recovered.

    Thus, four kinds of reference intensity decreases successively, and may be used in combination with the reference queue, the program statement by reference cycle more flexible control of the four-level objects.

  • finalize () method What is the use in the process of garbage collection?

    • First, a reachability analysis to determine a target is unreachable objects that it will not necessarily be recovered, a recovery process object should be at least twice marker, reachability analysis to determine when it will be unreachable mark once, and is called finalize () method, when about to be recycled will be marked once. The finalize () whether execution is conditional, if the finalize () method is not covered or have already done the will no longer enforced, but once the finalize () method performs, or is in the finalize () internal method to conduct a self-help by re-associated with GC Root avoid being recycled, and the opportunity for the next garbage collection when the object is no self-help, and this time is sure to be recycled. That finalize () method in this process played a role in the death of a determination to save themselves when faced with the object recovered.
    • finalize () method is also considered an external resource release manner, to make the final recycling, but it is used in the process object from the view of self: If an object is determined to be necessary to perform a finalize () method, then the object is put into a named among the F-queue queue, later made a virtual machine is automatically created and the low priority Finalizer thread to trigger its finalize () method, but at the same time in order to avoid finalize ( ) internal method performed slowly or occurrence of such a problem occurs that causes a cycle F-queue among other objects in the queue wait forever state, and even lead to system collapse Ben, Finalize () method will not necessarily be executed, it is obvious that this there is a call method of uncertainty, coupled with higher operating costs, resource recycling release is probably not enough stable, it is better to use try-catch methods or other means.
  • District method it is necessary to do garbage collection? why?

    Java Virtual Machine Specification limitation on the method very relaxed area, in addition to and do not require continuous outer Java heap as memory and may be selected or extended fixed size, garbage collection may choose not to implement, for storing the virtual machine has been loaded class information, constants, static variables, immediate post-compiler to compile the code and other data stored in the data life cycle is longer, even though this area is difficult to effect recovery is satisfactory, but in accordance with the provisions of the Java virtual machine specification, when when the method of memory allocation area can not meet demand, it will throw an OutOfMemoryError.

    Therefore, the method area in particular virtual machine is also necessary for garbage collection, garbage collection method for the recovery zone is mainly constant pool and unloading of the type of constant recycling of waste and useless class, will not continue to be as constant using the constant pool will be cleared, and the like will be recovered many conditions harsh, if all of the instances of a class has been recovered, the corresponding class loader is also recovered, and the corresponding class object is not referenced anywhere We can no longer be accessed from anywhere by means of reflection of this class, the class that can be recycled.

  • What OopMap that?

    GC Java virtual machine implementation may have different ways: If you had to select the type of virtual machine does not record any data, it can not distinguish between a location in memory where data is a reference type or other type, then realized in this case the GC is conservative GC; the JVM may choose not to record information on the type of station, the type of information stored on the object, is achieved by semi-conservative GC.

    And if it is accurate formula GC, from the outside at the type of information is not recorded, generating a mapping table , the virtual machine will be able to know the specific data of a location is what type , which is the use of a set of data called OopMap implementation of the HotSpot VM structure to achieve the object, the class loading when completed, will the HotSpot what the offset within an object what type of data is calculated, recorded in the JIT compilation process in a specific position in the stack and registers are what position reference, This information can then be directly obtained at the time of the GC scan. Different virtual machines can be achieved through different mapping table.

    reference

  • (Point safety and security zone in order to solve any kind of problem, what's the use?)

    HotSpot can be completed with the assistance of OopMap GC Root enumeration of reachability analysis is completed prior to garbage collection, but in order to ensure the accuracy of analytical results is required to suspend all execution threads in a process GC Root enumeration in order to avoid thread changes in the reference relationship appears implementation process, but if the instructions are generated for each corresponding OopMap, will occupy a lot of extra space, so the only record this information in a specific location, each method is JIT compiler will after some OopMap particular recording position, recording the time to execute an instruction of the method, the stack registers, and which is a reference position. Such GC will query these OopMap when scanning stacks to know where is quoted. The specific location of the main before the end of the cycle, method or temporary return calls after the call instruction method may throw an exception and the location, this location is called safe point , GC at the HotSpot can only point to enter into security . When GC occurs, the thread will execute a halt to the nearest safe point.

    Some, however, if the thread is blocked can not come to a halt security point of, in this case it is necessary to solve the security zone, in the area of ​​security code snippets referenced in relationships will not change, either in the region GC place to start is safe.

  • Common garbage collector which, respectively, what's the use?

    • Serial serial collector

      Serial Collector Collector is a single-threaded, it uses a CPU that is a collection thread to complete the work of garbage collection, garbage collection when it is necessary to suspend the work of all other threads, knowing that it collects end. When it collected during the work back to the other thread pause, but this simple and efficient way to define a single CPU environment, because it does not have the overhead of thread interactions, you can get the highest single-threaded garbage collection efficiency. Because under Client mode virtual machine memory management is generally small, Serial garbage collection pauses when other threads of time not too long, so for running in Client mode virtual machine is still very good.

  • ParNew collector

    ParNew collector is actually Serial collector multithreaded version, use multiple threads for garbage collection, many virtual machines running under Server mode of choice for the new generation garbage collector, and be able to work together with the old CMS's collector .

  • Parallel Scavenge collector

    Parallel Scavenge copy algorithm is to use a parallel multi-threaded new generation collector , it focuses on achieving a controlled highest possible throughput , i.e. the sum of the code to run a certain time garbage collection time with the time code running share, in the main usage scenarios for background operation without too much interactive tasks, a higher high throughput can be more efficient use of CPU time.

  • Serial Old collectors

    Serial Old collector's edition Serial old collector is to use mark - finishing single-threaded algorithms collector, it is mainly used for virtual machines under Client mode to use.

  • Parallel Old collectors

    Parallel Old is the Parallel Scavenge collector's version of the old, multi-threading and "mark - finishing" algorithm. Before this JDK1.6 collector appeared, Parallel Scavenge collector can not be used in conjunction with CMS collector, the collector can only select Serial Old garbage collect old age, and because of Serial Old collectors in the multi-CPU processing power and other more under optimal conditions of low hardware performance, to ensure that the advantages of high throughput Parallel Scavenge collector can not exhibit. With the Parallel Scavenge collector can later use Parallel Old collectors appeared in throughput and CPU resources to focus on sensitive occasions.

  • CMS collector

    CMS collector is a pause for the shortest recovery time objectives collector, the use of clear labeling - algorithm, and its garbage collection as a whole is concurrently executing threads and users, is a concurrent low pause collector, but very sensitive to CPU resources to deal with floating garbage, and the garbage collection completes a Full GC will have many pieces of space easily triggered.

  • (G1 collector)

    G1 collector is a tag-based sorting algorithm will not produce space debris, can precisely control the pause, the heap is divided into multiple fixed-size independent area, and track the extent of accumulation of garbage in these areas, in the background to maintain a priority list , each collection time according to the permitted region up garbage (garbage First) preferentially recovered.

  • Policy object assigned what?

  • What guarantees are allocated space?

Guess you like

Origin www.cnblogs.com/chen-ying/p/11407898.html