java garbage collection finishing

A garbage collector and finalize () 

 java garbage collector is responsible only for the recovery of useless objects occupy memory resources . But if your object is not created by the new (all the new objects are opened to heap resources in one place, easy to clean / manage resources), it will not know if the release of the object of this special memory. To address this situation, Object comes with a finalize () method.

  finalize () method of this principle is: Once the garbage collector ready to release the memory occupied by the object, it will first call the inherited / overridden fialize (), and call the method is not executed immediately recovered, but the next time ( JVM that require larger memory time ) when the recovery operation occurs, will really recovered memory occupied by the object. Therefore, the general himself rewrite fialize () method, it is important to do some cleanup work at the last moment recovered.

java garbage collection the following characteristics:

1, the object may not be garbage

   Objects do you create a certain function, such as displayed on the computer screen. So unless you special treatment erased from the screen, it can never be cleaned up. So if you do erase the screen in the process finalize () method, when garbage collection, finalize () is called, the screen image is clear. Please note: only the JVM garbage collector think time will need more memory to run ( although small overhead, but still has been running overhead ), so most of the recovery action is happening in that moment on the verge of running out of storage space, forced to run the JVM garbage collector. If the program to complete (or interrupt the operation), all those resources will be returned to the operating system.

2, garbage collection does not mean destructor

  This is the concept C, because java and C involved too, so often used to contrast. Simply put there is a thing called C destructor, the destructor must be performed before the object is destroyed. Here garbage collection does not represent destructor. finalize () function is similar, but not equal.

3, only memory-related garbage collection

  Here we must mentioned finalize () true purpose. Internal operation should be performed, and the method and memory recall, so fialize () method is not generic method. You might think that when members object contains object properties, finalize () should explicitly whether you want to clear those objects? Incorrect. It should be understood: no matter if the object is created, the garbage collector will be responsible for releasing all the memory occupied by the object. Therefore finalize () is typically treated by means other than the object to create storage space allocated for the object. Some say it's a mouthful, but an example will know.

  java source code to track when often encountered keyword native modification methods, which is also called "native method." When using these local methods, non-java code the way internal calls (not C is C ++). These non-code may be used malloc C of () family of functions to allocate storage space. So unless you call C the free () method, otherwise the storage space will not be freed. So you can call free to use native way finalize ().

  The above is the truth as little as possible is recommended rewriting finalize () of.

Second, the garbage collection

  Since fialize () Use scene so rare, then do not expect to frequently used fialize (). You have to create other cleaning methods, according to their own business cleaning. But fialize () has a feature that: the program calls it, is the object verification "end conditions". Also is to be marked, the object is dead, it can be recovered. For example: an object that represents a file open, in front of the object to be recovered programmers should close the file. As long as there has not been properly cleaned part of the object, there is obscure program deficiencies. fialize () can be used to find the final case.

 

 
 

// Using finalize() to detect an object that
// hasn't been properly cleaned up.

class Book {
  boolean checkedOut = false;
  Book(boolean checkOut) {
    checkedOut = checkOut;
  }
  void checkIn() {
    checkedOut = false; } protected void finalize() { if(checkedOut) System.out.println("Error: checked out"); // Normally, you'll also do this: // super.finalize(); // Call the base-class version  } } public class TerminationCondition { public static void main(String[] args) { Book novel = new Book(true); // Proper cleanup:  novel.checkIn(); // Drop the reference, forget to clean up: new Book(true); // Force garbage collection & finalization:  System.gc(); } }/* Output: Error: checked out *///:~

 

End of the conditions of this example is: all Book objects should be treated as checkIn before garbage collection. But in the main the inside, the second book is not checkIn, this time by finalize (), you can clearly know that the object did not deal with some clean before destruction. Further, the code used System.gc (); This is a mandatory garbage collection evoke machine to trigger the finalize BOOK (); Of course, if this is not mandatory evoke also, when the program runs to the large amount of memory is allocated when (you can create a large number of repeated BOOK), forcing the garbage collector automatically triggered. BOOK inherit if there is a parent, you want to trigger finalize the parent class (), you can use super.finalize (); call.

Third, how to work the garbage collector

  Inside the general impression, allocate new resources in the heap will be relatively slow, after all, can not be faster than the stack. But the fact is optimized JVM done a lot in this area, where the garbage collector to speed up the creation of objects, with obvious effect. That garbage collector to release storage space conducive to allocate storage space unused . Popular point that is, the more garbage collected memory, in theory, create objects will be faster (there are still critical, generally considered comparable to other languages to create objects on the stack, such as C). C heap is like a courtyard, each object inside each tube of each memory space. After a period of time an object is destroyed. It must be re-used space. In some JVM, heap like a conveyor belt, assign a new object, it will move forward one space. This means that space allocation is very fast (fast addressing). java addressing pointer simply moved to the unassigned region of the line, so that efficiency comparable velocity C allocated on the stack. Wherein the recording space objects "subscript" aspects of address, or some overhead, but need to find the heap than the C overhead is much smaller. In fact, java heap is not necessarily exactly like a conveyor belt, as this will cause frequent memory paging (memory is paged, when the flip is hard to be removed and placed on virtual memory). Paging can significantly affect performance, and ultimately, after you create enough objects, memory (lots of virtual memory is full) resource depletion.

  Here it is the turn of the garbage collector debut, when the garbage collector work, while reclaim the space, while the compact arrangement of objects in the heap. Such "heap pointer" can be easily moved closer to the beginning of the conveyor belt (java heap space is allocated advanced), will try to avoid the page fault. Rearrange garbage payback period would be subject to achieve high-speed, unlimited space (?) Reactor model that can be allocated.

The following is a garbage collection (more than java) three common design approach:

1, the reference count

  Each object contains a count application. When there is a reference to an object when the connection +1, when a reference goes out of scope or null assigned -1. Okay, so when the discovery of an object reference is 0, the space it takes up on the release (where there will be a space to 0 releases). Here there is a defect, if the object is a circular reference, i.e. a reference A B, B references A, appeared "objects can be recycled, but the reference count is not 0". For the garbage collector, the positioning of objects that reference each group of extremely expensive. In addition, the reference count management overhead is not big, but this will continue to occur throughout the application life cycle. The reference count is generally used to describe the way garbage collection, but not applied to any kind of JVM.

2、stop-and-copy

  This approach is to suspend the program ( not running in the background, but stopped the program, the garbage collection ), then so live objects from the current heap copy to another heap, and the rest are rubbish. When the object is copied to the new home (stack), next to one of these objects will, thus maintaining a compact arrangement of the new stack. Why this is payback JVM garbage in front of that virtual machine can do the compact arrangement of the objects. The copy process will produce new spending, as well as all references to the old point on the object must point to the new address. There may arise from non-referenced heap (not out of the new objects), these will be to find out traversing refer to the old heap when redirected to the new heap.

  Such recovery methods, inefficient . First, because the two have a heap, and stack objects to be transferred in two replicate, so this is actually twice as large maintenance space theory. For example, some JVM practice, several large block of memory allocated in the heap, where copying operation is carried out in a block of memory. Secondly, when the program is run after stabilizing, waste generated is relatively small, it may not even garbage. This time it is copied back and forth wasted. To avoid waste, JVM will be checked, and if no new waste generated, it is automatically converted into one mode.

3、mark-and-sweep

  Earlier versions of Sun's virtual machine is this. This way of thinking is from the stack and static storage area, through all the references, then you can find all the live objects. Whenever find a live objects, give the object a mark , remember a fortune. After all tags are done, clean up begins. When clean, unmarked objects will be released, copy action does not occur. This time the heap looks a bit like C, so if you want the rest of the objects in memory in a row, you need to refresh the rest of the object.

  

summary:

  Sun documents the garbage collection is seen as a low-priority background process, referring to because stop-and-copy: after all, to suspend the program. However, in earlier versions, JVM using the mark-and-sweep. Now both recovered by way of monitoring the JVM, if the object has been very stable, reducing the efficiency of the garbage collector, then it switches to the mark-and-sweep. Similarly, if the effect of mark-and-sweep is not good, there have been a lot of junk heap fragmentation (no reference objects), it will switch to the STOP-and-Copy . When stop-and-copy use, because the memory allocated to a large "block" as a unit, if the object is large, it takes up the entire block. Before the stop-and-copy run to stop the program run operation, will all live objects copied to the new block (heap), this time the old block will be discarded, the garbage collector can be discarded block copy the new object into the flexible use of resources. Each block has a respective algebraic (count) is recorded if it is still alive. If the block is referenced somewhere, count will increase. The garbage collector will assign a new action block after finishing the last recovery. The short-lived objects Dui helpful. Payback period will be complete garbage clean-up action on a regular basis ---- large objects are still not copied, or those blocks containing small objects are copied and finishing.

  JVM There are many additional techniques to increase speed. For example JIT (Just-In-Time) compiler technology. This program will translate all or part of the cost of the machine code, the program running speed and therefore a lot faster. When the need to load a class (class creates the first object, is not loaded again subsequently created), the compiler first find the corresponding class file, and the contents of the byte code into memory. This time, there are two ways to choose. One is to make all the JIT compiler code into machine code. However, since the occurrence of uncontrollable loading, is scattered in the entire life cycle of the program, would add up takes time, and increases the length of the executable code (bytecode JIT compiler to expand after the machine code is much smaller than that ), this may lead to memory paging, thus reducing the speed of the program. The second is lazy evaluation (lazy evaluatio), meaning that JIT compiled code only when necessary, so that the code will never be executed (import in, but not used) would they not be compiled JIT. Java HotSpot technology is the JDK uses a similar method, the code will be executed every time to do some optimization, so the more the number of executions, it's faster.

 

Guess you like

Origin www.cnblogs.com/lb-alex/p/11112483.html