Thinking in Java Notes (fifth chapter initialization and Cleanup (ii))

Source: Internet
Author: User

Fifth chapter initialization and Cleanup (II.) 5.5 cleanup: End-of-process and garbage collection

Cleanup work is often overlooked, and Java has a garbage collector responsible for reclaiming memory resources occupied by useless objects. However, there are special cases where the object (not using new) obtains a "special" area of memory, because the garbage collector knows only to release the memory allocated by new, so it does not know how to release special memory. Java allows you to define a method called Finalize () in the class, which works "assuming" the following:一旦垃圾回收器准备好释放对象占用的存储空间,首先调用其finalize()方法,并且在下一次垃圾回收动作发生时,才会真正回收对象占用的内存。

Java's Finalize () and C + + destructors are different, objects in C + + must be destroyed (if there are no flaws in the program), and objects in Java are not always garbage collected. That is: 1. Objects may not be garbage collected. 2. Garbage collection is not equal to "destruction"

Java does not provide a "destructor" or a similar concept, and to do similar cleanup, you must create a common way to perform cleanup work yourself. When "garbage collection" occurs (not guaranteed to occur), Finalize () is called, and the corresponding work is done, and if garbage collection does not occur, it is not called.

As long as the program is not on the verge of storage space, the control of the object will not be released, if the program execution ends, and the garbage collector has not released any objects you create storage space, as the program exits, the resources will be returned to the operating system. This strategy is appropriate because garbage collection itself consumes memory controls, and if not used, the memory overhead becomes smaller.

5.5.1 Finalize () use

Any behavior related to garbage collection (especially the Finalize () method), they must also be related to memory and recycling. The purpose of the Finalize () method is to reclaim special storage space outside of objects created with new, because in allocating memory, it is possible to adopt a similar approach in C, rather than the usual practice in Java (new). This occurs primarily when using local methods, where the local method is a way to invoke non-Java code in Java. Local methods currently only support C and C + +, but they can invoke code written in other languages.

In non-Java code, you might call the malloc () function family of C to allocate storage space, and unless you call the free () function, the storage space will not be freed, causing a memory leak. Free () is a function in C and C + +, so it needs to be called in Finalize () with a local method.

5.5.2, you have to clean up.

To clean up an object, the user must call the method that performs the cleanup action at a time when it needs to be cleaned. In C + +, all objects will be destroyed and should be destroyed. If a local object is created in C + + (that is, created on the stack, which does not work in Java), the Destroy action occurs at the end of the object scope at the boundary of "right curly brace". If the object is created with new, the destructor is called when the programmer calls the C + + delete operator (Java does not have this command). If delete is not called, the destructor is never called, and a memory leak occurs.

Local objects are not allowed in Java, and objects must be created using new. In Java, there is no release of the object's delete, and the garbage collector frees up storage space for you.

5.5.3 Termination conditions

You typically cannot expect finalize (), you must create additional "cleanup" methods, and explicitly call them. Finalize () also has a go-to usage, and does not depend on the call to finalize every time, that is, the validation of the object termination condition .

When an object is no longer interesting-that is, it can be cleaned up, the object should be in a certain state so that the memory it occupies can be safely freed. The following example demonstrates the possible use of Finalize ():

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");    }}public class Test {    public static void main(String[] args) {        Book novel = new Book(true);        novel.checkIn();        new Book(true);        System.gc();    }}

In this case, the end condition: All book objects should be checkin () before being garbage collected, but it is new Book(true) difficult to find this flaw if the object is not checkin and the finalization condition is not verified without finalize ().

System.GC () is used to force and terminate actions.

How the 5.5.4 garbage collector works

The garbage collector has an obvious effect on the speed of object creation, and when the Java Virtual machine is working, the release of the storage space affects the allocation of storage space, and because of the garbage collector, the speed at which Java allocates space from the heap can be comparable to the speed at which other languages allocate controls from the stack.

Understanding the garbage collection mechanism in other systems will help us to better understand the recycling mechanism in Java, which is a simple but slow garbage collection technique. Each object contains a reference counter that, when there are references and objects connected, has a reference count of 1 and a reference count minus 1 when the reference leaves the scope or is set to null.

The garbage collector iterates over the list of all objects, releasing the space it occupies when it finds that the reference count of an object is 0 o'clock (however, the reference technology pattern often releases the object immediately when the count value becomes 0). If there is a cycle of drinking between objects, the "object should be recycled, but the reference count is not 0" may appear. Reference counting is often used to illustrate how garbage collection works, but it seems never to be applied with any Java virtual machine implementation.

In some faster modes, the garbage collector is not based on reference counting techniques, but instead: to any "live" object, it must eventually be traced back to its reference that survives the stack or static storage. If you start from the stack and the static store, and iterate through all the references, you can find all the "live" objects, for each reference, you must trace the object associated with it, and then all references to the associated object, repeatedly, until it is all accessed.

In this way, the Java virtual machine will employ an adaptive garbage collection technology. One of the methods to find the surviving object is called stop-copy (stop-and-copy). Obviously this means pausing the program first (not in the background recycle mode), and then copying all the surviving objects from the current heap to the other heap, which should be reclaimed without being copied.

When moving objects from one place to another, all of its references must be amended. References that reside in a heap or static store can be corrected directly, but there may be other references to those objects that can be found during traversal. For this type of replication collector, efficiency is reduced. 1. Requires two heap back and forth Daoteng, some Java virtual machines deal with this problem by allocating a few large chunks of memory from the heap on demand, and the copy action occurs between these large chunks of memory. 2. The program enters a stable state, resulting in a small amount of garbage, but the copy-type collector will continue to replicate, for the second case, some Java virtual opportunity to check: if there is no new garbage generated, it will switch to another mode of Operation (Mark-sweep Mark-and-sweep) , the technology was used by Sun's earlier versions of Java virtual machines. For general purposes, the "mark-sweep" approach is quite slow, but it can be very fast when only a small amount of garbage is generated and no garbage is generated.

tag-sweep is based on the same idea of starting from the stack and static storage, traversing all references, and then finding all the surviving objects. Whenever a surviving object is found, a tag is set for the object, and no objects are reclaimed in the process. The cleanup will only begin when all marks have been completed. During the cleanup process, objects that are not marked are all freed and no copy action occurs. The rest of the space is discontinuous, and the garbage collector has to rearrange the remaining objects if it wants to have a continuous space.

stop-copy means that this garbage collection mechanism does not take place in the background. When the garbage collection action occurs, the program is stopped, and in Sun's documentation, many references treat garbage collection as a low-priority background process, but in fact early-morning Sun's Java Virtual machine is not garbage collected in the background, but when there is less available memory, The sun version of the garbage collector pauses the program, and the same flag-sweep must be done in case the program is paused.

In a Java virtual machine, memory allocation is in a larger "block" unit, strictly speaking, "stop-copy" requires that all surviving objects must be copied from the old heap to the new heap before the old object is disposed, and after the garbage collector can copy the objects into the discarded blocks when it is recycled, each block is algebra (generation count) to record whether it still survives. The garbage collector periodically conducts full cleanup actions – large objects are still not copied (only their algebra is incremented), and the chunks of the small objects are copied and organized. Java virtual opportunities are monitored and switched between "tag-sweep" and "stop-copy", which is "adaptive" technology.

There are many additional techniques for increasing speed in Java virtual machines, especially those related to loader operations, called "Instant (Just-in-time,jit)" compilers. It can translate all or part of the program into a local machine code (which would have been the work of a Java Virtual machine), and the program is running faster. When a class needs to be mounted (usually the first object of the Class), the compiler first finds the. class file and then loads the bytecode into memory. Next there are two options to choose from:

    • Let the instant compiler compile all of the code, which is scattered throughout the program declaration cycle, adds up to more time, and increases the length of the executable code.
    • The other is lazy evaluation (lazy evaluation), meaning that the immediate compiler compiles the code only when necessary, so that code that does not execute is not JIT-compiled.

Thinking in Java Notes (fifth chapter initialization and Cleanup (ii))

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.