Reading notes ----- JVM garbage disposal mechanism

xiaoxiao2021-03-05  24

When writing Java code, we do not need to manually delete the object and the memory address of the object and the recovery object as you have in C . Because there is a garbage collection mechanism in Java. Java, when there is no object reference When it is directed to the memory that is originally assigned to an object, the memory is garbage. A system-level thread for JVM will automatically release the memory block. Garbage collection means that the object is no longer needed is "useless information", which will be discarded. Waste collection can automatically release memory space and reduce the burden of programming. Algorithm analysis of garbage collection

Java language specification did not clearly show which garbage collection algorithm used JVM, but any garbage collection algorithm generally do 2 basic things: (1) Discover useless information objects; (2) Recycling memory space occupied by useless objects Make the space can be used again.

Most garbage collection algorithms use the root set; the so-called root set will be the collection of reference variables that are being executed (including local variables, parameters, class variables), and programs can use reference variables to access Object properties and methods of calling objects. Waste collection The preferred need to determine which of the roots is getting up to which is unreachable, from the root set of accessible objects are active objects, which cannot be recycled as garbage, which also includes indirect access from roots. . The root set is in line with the conditions of garbage collection through any path, and should be recycled. Here, several common algorithms are described below.

Reference Counting Collector

The reference count is the only garbage collection that does not use the root set, which uses a reference counter to distinguish the living object and the no longer used object. In general, each object in the heap corresponds to a reference counter. When an object is created every time, the reference counter is set to 1 when it is assigned to one variable. The reference counter plus 1 is added when the object is assigned to any variable. When the object is a role (the object is not reused), the reference counter minus 1. Once the reference counter is 0, the object satisfies the conditions for garbage collection.

The garbage collector based on the reference counter is faster, and the program must be run in real time when the garbage collector is running fast. However, the reference counter adds the overhead of the program execution, because each object gives a new variable, the counter adds 1, and each existing object has an action domain, the counter minus 1.

Tracing Algorithm (Tracing Collector)

The TRACING algorithm is to solve the problem of reference counting, which uses the concept of root set. The garbage collector based on the Tracing algorithm starts scanning from the root set, identify which objects are up to, which objects are not reached, and the accessible object is marked in some way, such as setting one or more bits for each accessible object. During scanning recognition, waste collection based on Tracing algorithm is also referred to as markers and cleaning (Mark-Sweep) garbage collectors.

Compacting Collector

In order to solve the slabrish problem, Tracing-based garbage-based absorbing the idea of ​​the Compacting algorithm, in the process of cleaning, the algorithm moves all the objects to one end, the other end of the heap turns an adjacent free memory area The collector will update all the references to all objects that move, so that these references can identify the original object in the new location. In the implementation of a collector based on a Compacting algorithm, a handle and a handle are generally added.

COPING Collector

The algorithm is proposed to overcome the overhead of the handle and resolve the garbage collection of the stack of fragments. When it starts to divide a heap into a target plane and a plurality of idle surfaces, the program allocates space from the object surface, when the object is full, the garbage collection based on the Coping algorithm is scanned from the root set, and each activity object is copied To the empty surface (there is no idle hole between the memory occupied by the active object), such an idle surface becomes an object surface, the original object surface has become an idle surface, and the program will allocate memory in the new object. A typical garbage collection of Coping algorithm is a stop-and-copy algorithm that divides the stack into the object surface and the idle area, and the program is suspended during the switching process of the object surface and the idle area.

Generation Algorithm

A defect in the stop-and-copy garbage collector is that the collector must copy all the activity objects, which adds the program waiting time, which is the reason why the Coping algorithm is inefficient. There is such law in the programming: Most objects have a short time, and a few have a long time. Therefore, the Generation algorithm divides a heap into two or more, each subtle is used as a generation of the object. Since most objects exist shorter, the garbage collector will collect these objects from the youngest subtle as the program discards the objects that are not used. After running the specified garbage collector, the last running object moved to the next highest generation, because the old generation of subaps will not be recycled, thereby saving time.

Adaptive Algorithm

In a particular case, some garbage collection algorithms are better than other algorithms. The garbage collector based on an Adaptive algorithm is to monitor the usage of the current stack and will select the garbage collector for the appropriate algorithm. Command line parameters Perspective of the garbage collector

Using System.gc () can request Java garbage collection in JVM using the algorithm for JVM. There is a parameter -verbosegc in the command line to see the plot of the pluck used by Java, and its format is as follows:

Java -verbosegc ClassFile

Class test

{

Public static void main (string [] args)

{

NEW test ();

SYSTEM.GC ();

System.Runfinalization ();

}

}

Java -verbosegc test

Execution: [Full GC 168K-> 97K (1984K), 0.0253873 Secs

The data before and after the arrow indicates the memory capacity used before and after the garbage collection GC, indicating that the capacity of 168K-97K = 71K is reclaimed.

Finalize method Perspective The running of the garbage collector is before collecting an object, generally requires the program to call the appropriate method to release the resource, but in the case where the resource is not explicitly released, Java provides the default mechanism to terminate the object heart. Release resources, this method is Finalize (). It is necessary to use Finalize () because sometimes there is a way to take different ways to Java, do some C style. C and C are the only language that is currently supported by inherent methods. However, because they can call subroutines written in other languages, anything can be effectively called. Inside the non-Java code, you may call the malloc () series function to allocate storage space with it. Moreover, unless free () is called, the storage space will not be released, resulting in the appearance of memory "vulnerability". Of course, Free () is a C and C functions, so we need to call it in a inherent method within Finalize (). That is to say we can't use Finalize () too much, it is not an ideal place for ordinary clearance. Class chair {

Static Boolean Gcrun = False;

Static boolean f = false;

Static int created = 0;

Static int finalized = 0;

INT I;

Chair () {

i = created;

IF (create == 47)

System.out.println ("CREATED 47");

}

protected void finalize () {

IF (! gcrun) {

Gcrun = true;

System.out.println (

"Beginning to Finalize After"

Created "Chairs Have Been Created");

}

IF (i == 47) {

System.out.println (

Finalizing Chair # 47, "

"Setting Flag to Stop Chair Creation";

f = true;

}

Finalized ;

Finalized> = created)

System.out.println (

"All" finalized "finalized");

}

}

Public class garbage {

Public static void main (String [] args) {

IF (args.length == 0) {

System.err.Println ("USAGE: / N"

"Java Garbage Before / N OR: / N"

"Java Garbage After");

Return;

}

While (! chair.f) {

New chair ();

New String ("To Take Up Space");

}

System.out.println (

"After All Chairs Have Been Created: / N"

"Total Created =" chair.created

", Total Finalized =" chair.finalized); if (args [0] .equals ("before")) {

System.out.println ("GC ():");

SYSTEM.GC ();

System.out.println ("Runfinalization ():");

System.Runfinalization ();

}

System.out.println ("BYE!");

IF (Args [0]. Equals ("after")))

System.RunfinalizersoneXIT (TRUE);

}

}

Regarding the above-mentioned instructions on garbage collection, it can be found that there are several features of garbage collection: (1) Unpredictability of garbage collection: Due to different garbage collection algorithms and uses different collection mechanisms, So it may be timing, it is possible to occur when the system idle CPU resource occurs, and it may be the same as the original garbage collection. When the memory consumption has the limit, this is the selection and specific settings of the garbage collector. There are relationships. (2) Accuracy of garbage collection: mainly includes 2 aspects: (a) The garbage collector can accurately mark the live object; (b) the garbage collector can accurately position the reference relationship between the objects. The former is the premise of completely recovering all discarded objects, otherwise it may cause memory leakage. The latter is a necessary condition for realizing algorithms such as mergers and replication. All irreparable objects can be reliably recycled, all objects can be reassigned, allowing the object's replication and object memory, which effectively prevents the memory of memory. (3) There are now many different garbage collectors, each with its algorithm and its performance, both stop the operation of the application when garbage collection starts, and the application is allowed when garbage collection begins Thread operation, as well as the same time garbage collection multi-thread operation. (4) The implementation of garbage collection and the specific JVM and JVM memory model have a very close relationship. Different JVMs may adopt different garbage collection, while the JVM memory model determines which types of garbage can be used. Now, the memory system in the HotSpot series uses advanced object-oriented framework, which makes the series of JVMs can be collected by the most advanced garbage. (5) With the development of technology, modern waste collection technology provides many optional garbage collectors, and different parameters can be set when each collector is configured, which makes optimal applications according to different application environments. Application performance is possible. For the above characteristics, we should pay attention when we use: (1) Do not try to assume the time of garbage collection, this is unknown. For example, a temporary object in the method becomes a useless object after the method is completed, and this time it can be released. (2) Some classes and garbage collection are provided in Java, and provide a method for forcing garbage collection - calling system.gc (), but this is also an uncertain way. Java does not guarantee that each call will be able to start garbage collection, but it will only send a request to the JVM. If you really implement garbage collection, everything is an unknown. (3) Pick the garbage collector suitable for you. In general, if the system does not have special and harsh performance requirements, the Default option for JVM can be used. Otherwise, consider using targeted garbage collectors, such as incremental collectors, is more suitable for systems with high real-time requirements. The system has a high configuration, there are more idle resources, consider using parallel tag / clear collectors. (4) The key to it is difficult to grasp the problem of memory leakage. Good programming habits and rigorous programming attitudes will always be the most important, don't let your small mistake caused a large vulnerability in memory. (5) Release the reference to the useless object as soon as possible. Most programmers are using temporary variables, and the reference variable is automatically set to NULL after exiting the activity domain (Scope), implies the garbage collector to collect the object, and pay attention to whether the reference is listened, If so, you have to drop the monitor and then assign a null value.

转载请注明原文地址:https://www.9cbs.com/read-32187.html

New Post(0)