Java interview problem finishing-garbage collection

Source: Internet
Author: User
Tags compact

For GC, when a programmer creates an object, the GC starts to monitor the object's address, size, and usage. Typically, a GC uses a graph to record and manage all objects in the heap (heap) in such a way as to determine which objects are "accessible" and which are "unreachable". However, in order to ensure that the GC can be implemented on different platforms, the Java specification does not strictly govern many of the GC's behavior. For example, there are no clear rules as to what type of recovery algorithm to use, when to recycle, and so on. Therefore, different JVM implementations often have different implementation algorithms. (Whenever an object is disposed, all references to the object are assigned null)

--------------------------------------------------------------------------------------------------------------- --

Garbage collection reclaims objects that occupy a memory space instead of objects.

The purpose of garbage collection is to identify and discard objects that the app is no longer using to free and reuse resources. When an object is not reachable through the root collection (found) in the JVM's running space, the object is called a garbage object , and the object can be recycled.  a root collection consists of a static reference field in a class and a local reference domain, which is indexed by the JVM through the root collection. The garbage collector calls the object's Finalize () method before releasing the memory occupied by the object, and it is generally recommended that the resources held by the object be disposed of in the method. If the object's reference is set to NULL, the garbage collector does not immediately release the memory occupied by the object, which will be recoverable in the next garbage collection cycle. Calling the System.GC () method can greatly affect system performance.

--------------------------------------------------------------------------------------------------------------

In general, focus on two things: heap memory and stack memory . Heap memory is primarily used to store objects and variables that are created or instantiated by the program at run time, such as objects created with the New keyword. The stack memory is used to store methods declared as static or non-static in the program code.

The Java heap is more like a conveyor belt, and every new object is allocated, it moves one cell forward. This means that the object storage space is allocated fairly quickly. Java's "heap pointers" are simply moved to areas that have not yet been allocated. That is, when allocating space, the "heap pointer" moves forward regardless of whether or not the object is to be disposed of later. It would be nice if the program exited before the available memory ran out, so the garbage collector would not be activated at all.

The stack is left to the JVM for its own use to hold the information of the class, unlike the heap, where the GC does not free up space during the run time, and when the scope of the variable is exceeded, Java automatically frees the allocated memory space for that variable:

1. If the program declares a variable of static, it runs directly on the stack, the process is destroyed, and the static variable is not necessarily destroyed.
2, the basic type variables defined in the function and the reference variables of the object are allocated in the function's stack memory

The advantage of a heap is that it can dynamically allocate memory size, and the lifetime does not have to tell the compiler beforehand because it allocates memory dynamically at run time. The disadvantage is that the memory is dynamically allocated at runtime and the access speed is slow.
The advantage of the stack is that the access speed is faster than the heap, and the disadvantage is that the data size in the stack and the lifetime must be deterministic without flexibility.

--------------------------------------------------------------------------------------------------------------- ---------------------------------------------

The JVM's heap is the run-time data area, and all instances and arrays of classes are allocated memory on the heap. It is created when the JVM is started. The heap memory that the object occupies is reclaimed by the automatic memory management system, which is the garbage collector. Heap memory is made up of surviving and dying objects. The surviving objects are accessible to the app and are not garbage collected. The object of death is the object that the app is inaccessible and has not been reclaimed by the garbage collector. Until the garbage collector reclaims these objects, they will occupy the heap memory space.

---------------------------------------------------------------------------------------------------------------

In the JVM runtime, the entire life cycle of an object can be broadly divided into 7 phases:
The creation phase, (1) allocates storage space for the object, (2) constructs the object, (3) initializes the static member from the superclass to the subclass , and (4) the superclass member variable is initialized sequentially, and the constructor method of the superclass is called recursively; (5) The subclass member variables are initialized sequentially, and the subclass constructs the method call.
Application Phase : (1) The system maintains the >=1 Strong reference of the object (strong Reference); (2) All references to the object are strongly referenced (unless we are shown to apply: Soft reference (Soft Reference), weak reference (Weak Reference), or virtual reference (Phantom Reference).

-----------------------

Strong references: Generic references are strong references. The object is created by using the new method, and the associated object is displayed.
Soft references: This kind of memory is only recycled when there is not enough memory, so when memory is sufficient, they are usually not recycled, and if the memory space is insufficient, the memory of those objects is reclaimed. Soft references can be used to implement memory -sensitive caches .

Weak reference: When the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, the memory is reclaimed regardless of the current memory space or . However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.  

Virtual Reference: A virtual reference does not determine the life cycle of an object, it refers to objects that have completed the Finalize function and are not reachable by the GC, but have not yet been recycled by the garbage collector. If an object holds only virtual references, it can be garbage collected at any time, just as there are no references. Virtual references are primarily used to track the activities of objects that are garbage collected . This kind of object can assist finalize in some later recycling work, we enhance the flexibility of the resource recycling mechanism by covering the refernce clear () method. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled.

Weak references and virtual references are seldom used in the actual program design, and there are many cases with soft references, because soft references can speed up the JVM's recovery of garbage memory, maintain the security of the system, and prevent the problems such as memory overflow.

-------------------
The non-visual stage
, which is no longer referenced in the code in the other region, has been removed from its strong reference.
Unreachable stage;
(there are two ways to know whether this object is referenced: The first is to traverse the object on the heap for reference, and the second is to traverse the stack or static store to find the object.) Java, which uses the latter, can no longer find direct or indirect strong references in the virtual machine's object reference root collection, which are typically temporary variables for all line stacks. All static variables that have been loaded or are references to local code interfaces.
The stage of collection can be collected;
The end stage;
Release phase

The <1> collector found that the object was not reached.
The <2> Finalize method has been executed.
<3> object space has been reused.

-------------------------------------------------------------------------------------------------------------

Garbage collection algorithm:

Mark-sweep (Mark-purge) algorithm: Two stages: Mark phase and purge phase. The task of the tagging phase is to mark out all objects that need to be recycled, and the purge phase is to reclaim the space occupied by the tagged objects. Easy to generate memory fragmentation.

Copying (copy) algorithm: it divides available memory by capacity into two blocks of equal size, using only one piece at a time. When this piece of memory is used up, copy the surviving object to another piece, and then clean up the used memory space once, so the memory fragmentation problem is not easy. Memory is reduced to half the original. The efficiency of the copying algorithm is very much related to the number of surviving objects, and if there are many surviving objects, the efficiency of the copying algorithm will be greatly reduced.

Mark-compact (marker-collation) algorithm: The tagging stage is the same as mark-sweep, but after the token is completed, it does not clean the recyclable object directly, but instead moves the surviving object to one end and then cleans up memory outside the end boundary.

generational Collection (generational collection) algorithm: Its core idea is to divide the memory into several different regions based on the life cycle of the object's survival. In general, the heap zoning is divided into the old age (tenured Generation, only a small number of objects need to be recycled per garbage collection ) and the new generation (young Generation, every time a garbage collection has a large number of objects to be recycled, you can take the most appropriate collection algorithm according to the characteristics of different generations.

--------------------------------------------------------------------------------------------------------------- ---

    The new generation have adopted copying algorithm, because each garbage collection in the Cenozoic to recover most of the objects, that is, the number of operations need to replicate less, but the actual is not in accordance with the proportion of 1:1 to divide the new generation of space, In general, the Cenozoic is divided into a larger Eden space and two smaller survivor space, each time using Eden space and one of the survivor space, when recycling, Copy objects that are still alive in Eden and survivor to another survivor space, and then clean up Eden and the survivor space you just used.

The old-age feature is that only a small number of objects are recycled per collection, typically using the mark-compact algorithm. 】

New Generation : The newly created objects are stored here. Because most objects quickly become unreachable, most objects are created in the young generation and then disappear. When the object disappears from this memory area, we say that a "minor GC" occurred.

Old Age : Not become unreachable, surviving young generation objects are copied here. This area of memory is generally larger than the younger generation. Because of its larger size, GC occurs less often than in younger generations. When the object disappears from the old age, we say "major GC" (or "fullGC") has occurred.

New Year's--the old age

The young generation has a total of 3 spaces, of which 2 are Survivor area. The order of execution for each space is as follows:

      1. The vast majority of newly created objects are allocated in the Eden area.
      2. Once a GC occurs in the Eden area, the surviving object is moved to one of the survivor areas.
      3. Once a GC occurs in the Eden area, the object is stored in the Survivor area, where other surviving objects already exist in the survivor area.
      4. Once a survivor area is full, the surviving object moves to another survivor area. Then the previous space is full survivor the area will be empty, without any data.
      5. Objects that are still alive after repeated steps like this will be moved to the old age.

--------------------------------------------------------------------------------------------------------------- ---------------------

Java Virtual machines Adopt an "adaptive" garbage collection Technology

Java has two types of surviving objects found :

(1) stop-copy: suspends the operation of the program (so it is not in background recycle mode), and then copies all the surviving objects from the current heap to the other heap, without being copied all garbage.

(2) tag-sweep: from the stack and static storage, traverse all references to find all the surviving objects. Whenever it finds a surviving object, it will give the object a token. No objects are recycled during this process.

  Adaptive : when the garbage collector starts for the first time, it performs a "stop-copy" because there is too much garbage in the memory at this time. Then the Java Virtual opportunity is monitored, and if all objects are stable and the garbage collector becomes less efficient , switch to the "tag-sweep" approach, and the Java Virtual Opportunity tracks the "mark-sweep" effect, if the heap space is fragmented, Will switch to the stop-copy mode. This is called "adaptive" technology.

--------------------------------------------------------------------------------------------------------------- -----------------------

    • Reference counting method

Each object has a reference count, the object is referenced once, the reference counter is + 1, the object reference is disposed, reference counter-1, until the object has a reference count of 0, and the object is identified to be recyclable.

    • Root Search algorithm

This algorithm currently defines several root objects that are objects that are not recycled by the JVM virtual machines, so objects that refer to (strong references) are objects that are in use, objects that are not used by objects that are about to be reclaimed. Simple is to say: If the object can reach root, it will not be recycled, if the object can not reach root, it will be recycled.

The following objects are considered to be root objects:

      • Classes loaded by the startup class (bootstrap loader) and objects created
      • Objects referenced by the JVM Runtime method area class static variable (static)
      • The JVM runtime method goes to the object referenced by the constant pool
      • The JVM currently runs the virtual machine stack variable table reference object in the thread
      • Objects referenced in the local method stack (JNI)

--------------------------------------------------------------------------------------------------------------- -------------

Java interview problem finishing-garbage collection

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.