//Garbage.java
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);
}
}
Java heap management - Garbage Collection Author: Author Liu Chao Liu Chao, Department of Computer Science, Huazhong Normal University and the Institute of communications networks, you can contact him by shuechao_lau@hotmail.com. 1 Introduction Java's heap is a runtime data area, an instance of a class (object) allocates space. All objects established by the Java Virtual Machine (JVM) are stored, which are established by Directives such as New, NEWARRAY, ANEWARRAY, and MULTIANEWARRAY, but they do not need program code to explicitly release. In general, the stack is responsible by garbage collection. Although the JVM specification does not require special garbage collection technology, it does not even need garbage collection, but the JVM is realized when it is realized due to the finish of memory. The pile managed by garbage recycling. Garbage Recycling is a dynamic storage management technology that automatically releases objects that are no longer referenced by programs, and implements resource automatic recycling according to specific garbage collection algorithms. 2 The meaning of garbage collection is occupied in C , and the inside of the object has been occupied before the program ends running. It cannot be assigned to other objects before explicitly release; in Java, when there is no object reference pointing to an object When memory, the memory becomes 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. When an object is no longer referenced, the memory reclaims the space it occupies so that the space is used later. In fact, in addition to the use of useless objects, garbage collection can also clear the memory record fragment. Since the memory space accounted for the discard object is created, the memory will be fragmented. Debris is an idle memory hole assigned to the memory block of the object. Defragmentation The hinders of the hinders are stored in one end of the stack, and the JVM assigns the memory to the new object. Waste collection can automatically release memory space and reduce the burden of programming. This has some advantages to the Java virtual machine. First, it enhances programming efficiency. When there is no garbage collection mechanism, it may cost a lot of time to solve a difficult memory problem. When programming with Java language, the garbage collection mechanism can greatly shorten the time. Second, it is an important part of its integrity and garbage collection is an important part of the Java language security policy. A potential disadvantage of garbage collection is its overhead affecting program performance. The Java virtual machine must track the useful objects in the running program, and finally releases the useless objects. This process needs to spend the processor time. Secondary garbage collection algorithm is incomplete, and some garbage collection algorithms used earlier cannot guarantee 100% to collect all waste memory. Of course, as the continuous improvement of the garbage collection algorithm and the continuous improvement of the efficiency of hardware and software, these issues can be solved. 3 Algorithm for garbage collection: Java language norms 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 The memory space occupied in useless objects allows the space to 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. 3.1 Reference Counting Collector The reference count is the only garbage collection without the root set, which uses the reference counter to distinguish the survival object and the object that is no longer used.
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 a domain born, the counter minus 1.3.2 Tracing algorithm is In order to solve the problem of reference counting, it 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 the scanning recognition process, garbage collection based on Tracing algorithm is also called mark-and-swhere garbage collector .3.3 Compacting algorithm (Compacting Collector) In order to solve the stack of fragmentation, Tracing-based garbage recycling absorbed Compacting The idea of the algorithm, during the clear process, the algorithm moves all the objects to one end of the stack, the other end of the heap turns an adjacent idle memory area, and the collector will perform all the references to all objects. Update allows these references to 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. 3.4 COPING Algorithm This 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. 3.5 Generational Collector Stop-And-Copy Garbage Collector's Defects is that the collector must copy all active objects, which adds the program waiting time, which is the reason for the Coping algorithm. 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. 3.6 Adaptive Algorithm In a specific case, some garbage collection algorithms will exceed 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. 4 Perspective Java Garbage Recycling 4.1 Command line parameter Perspective Trash of Waste Collectors You can request Java garbage recycling regardless of the junk recycling of JVMs.
In the command line, there is a parameter -verbosegc to see the case of the pluck used by Java, its format is as follows: java -verbosegc classfile can see an example: Class TestGC
{
Public static void main (string [] args)
{
NEW TESTGC ();
SYSTEM.GC ();
System.Runfinalization ();
}
}
In this example, a new object is created because it is not used, so the object is quickly changed, after the program is compiled, the execute command: Java -verbosegc testGc results are: [Full GC 168K-> 97k ( 1984K), 0.0253873 SECS]
The machine's environment is, Windows 2000 JDK1.3.1, the data before and after the arrows 168k and 97k indicate the memory capacity used before and after the garbage collection GC, indicating that there is 168K-97K = 71k object capacity is reclaimed, the data within parentheses 1984K is the total capacity of the heap memory, the time required for collecting is 0.0253873 seconds (this time will vary when executed each time). 4.2 Finalize Method Perspective The operation of the garbage collector before the JVM garbage collector collects an object, generally requires the program to call the appropriate method to release the resource, but Java provides the default mechanism to terminate the object without explicitly release the resource. The heart releases the resource, this method is Finalize (). Its prototype is: protected void finalize () throws throwable
After the Finalize () method returns, the object disappears, and the garbage collection starts. Throws throwable in the prototype indicates that it can throw any type of exception. It is necessary to use Finalize () because sometimes there is a way to take different ways to Java, do some C style. This can be carried out by "inherent methods", which is a way to call non-Java methods from Java. 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. In normal clearing work, to remove an object, the user of the object must call a clear method in a location where you want to clean it. This is slightly in touch with the concept of C "destroyer". In C , all objects are broken (clear). Alternatively, in other words, all objects should be "should" destroy. If C object creates a local object, for example, created in the stack (it is impossible in Java), then clear or destroy the work of the "endparent bracket", create this object's scope of the field get on. If the object is created with NEW (similar to Java), then the corresponding destroyer is called when the programmer calls the C DELETE command (Java without this command). If the programmer has forgotten, then never call the destroyer, we will finally get a memory "vulnerability", and other parts of the object will never be cleared. Instead, Java does not allow us to create local (local) objects - no matter how you use New. But in Java, there is no "delete" command to release the object, because the garbage collector will help us freely release the storage space. So if we stand in a more simplified position, we can say that Java has no destructive device because there is a waste collection mechanism. However, as learned in the future, it will know that the existence of the garbage collector does not completely eliminate the needs of the destroyer, or the need to eliminate the mechanism of the destroyer (and absolutely can't call Finalize () So try to avoid it). If you want to perform some other forms of cleaning other than releasing storage space, one method in Java must still be called. It is equivalent to C destroyer, but it is not convenient. The following example shows you the process of garbage collection, and summarized the previous statement. 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);
}
}
The above program created a lot of Chair objects, and some time after the garbage collector started running, the program stopped creating a chair. Since the garbage collector may run at any time, we can't know when it starts. Therefore, the program uses a mark named GCRUN to indicate whether the garbage collector has started running. With the second tag F, Chair can tell main () it should stop the generation of the object. Both of these tags are set in Finalize (), which is called during garbage collection. The other two static variables --created and finalized - the number of objects used to track the number of objects that have been created and the number of objects that have been finished in the garbage collector. Finally, every chair has its own (non-Static) INT I, so how much it can be tracked to understand the specific number. After the number of 47-numbered CHAIR is finished, the tag will be set to TRUE, and finally end the CHAIR object's creation process. (For more specific analysis and description of this example, please refer to "Java Programming Thoughts" Chapter 4) 5 Reix for garbage collection After the above description, it can be found that there are several features of garbage collection: (1) Unexceptable in garbage collection: Since different garbage collection algorithms are achieved, it may be timed, it is possible to occur when the system is idle CPU resource occurs, and it may be and the original Like the garbage collection, when the memory consumption has the limit, this is related to the selection and specific settings of the garbage collector. (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.