Java learning notes (release of objects)

Source: Internet
Author: User

For basic type variables, because they are all allocated in the memory stack, release is not a problem and will be released in a timely manner. But for reference types, it is different.
Java provides a basic object memory recycle mechanism-the Garbage Collector. Let's take a look at how it works:
First, we must understand that variables of the reference type, like those of the basic type, are allocated to the memory stack, but the variables of the reference type are saved in the stack.
A reference address (pointer). The heap memory referred to by this reference address is the actual object storage zone.
Java Garbage Collector for JavaProgramIt is an external program and runs independently. Therefore, there must be a mechanism for the garbage collector to know which objects (in the heap)
It is no longer used. The simplest method is to reference and count objects:
When an object is referenced by an object variable, the reference count of the object is increased by 1. If the reference variable of an object (in the stack) exceeds the lifetime, the reference count of the object is released.
In this way, the garbage collector can determine whether the object can be withdrawn Based on the object reference count. It seems that this method is indeed relatively simple, but in fact,
There are still many problems with this method:
1) if the object variables are in the stack, the above mechanism is of course correct. But in fact, the object variable can be a member of another object, and the object itself can also contain other
The member variables of the object type form a complex reference network. This reference network may also contain cyclic references, which can easily lead to
Some objects will not be recycled throughout the program running, resulting in a large amount of memory leakage;
2) synchronization problems. When the garbage collector is working, if the program is also working, it is also allocating or manipulating objects. For example, although the reference count of an object is 0
The recycler recycles this object, but at the same time, this object is referenced to a new object variable, which produces unpredictable errors. To prevent such conflicts
When the receiver is working, the program must stop working. This will bring about another problem, reducing the program running efficiency.

Currently, this method of garbage collection using object reference counting is rarely used independently.

another method is to use Object Tracking Technology:
when the garbage collector is working, it traverses object references starting from the reference variables in the program stack memory and marks that the object is reachable. Then, inaccessible objects can be recycled.
This method solves the problem of loop reference, which is highly efficient, but also has the following problems:
1) the problem of synchronization between the garbage collector and the program is not solved, the program must stop running when the garbage collector is working.
2) during each garbage collection, all objects must be traversed for a long time.

Of course, there are still many garbage collection policies. You can search for them. Although garbage collection is transparent for programmers for most of the time, you can understand these mechanisms.
It provides a reference for us to solve practical problems.
For programmers, there are two aspects that must be concerned with, regardless of the recycling mechanism:
1) When will our objects be recycled (the garbage collector is uncontrollable );
2) The objects produced by Java are okay, but we allocate our own memory (mainly by calling other languagesCodeLibrary, such as C ++.
The garbage collector is triggered based on its monitoring of memory usage. Garbage collection is triggered only when the memory space is smaller than a threshold value. In most cases
This is not a problem, but if our objects use third-party scarce resources, such as database links, or we need to clear some resources when the objects are released (for example, erased on the Interface
Drawing) work, what should we do? One way is to take the initiative, such as database links and printer release, but in some cases, we still cannot take the initiative, such
An object uses a database link, but this object is shared by multiple other objects, so it is difficult for you to take the initiative to release the link. In this case, Java provides another mechanism,
It is to provide a finalize () method for each object, which is called by the garbage collector (although you can call it yourself, it is not recommended to do so because it is similar to failing to take the initiative ).
In this way, you can perform cleanup after the object is released in this method. Note that the garbage collector has restrictions on calling the finalize () method. For example, each object only calls
Therefore, we must pay attention to the problems brought about by the object "Resurrection.
When will our objects be recycled? Although we can call the system. GC () method to recommend (note, it is only recommended) the Garbage Collector for recycling, it is actually
For us, it is still uncontrollable, so:
1) We should take the initiative to release resources, especially scarce resources;
2) When calling other language code libraries, we should also take the initiative to release objects. If not, at least we should do so in the finalize () method;

The following example is a copybook to demonstrate the uncertainty of garbage collection (I made some changes ):

Public class chair {static Boolean created UN = false; static Boolean F = false; static int created = 0; static int finalized = 0; int I; Chair () {I = ++ created; If (created = 47) system. out. println ("created 47");} protected void finalize () {If (! Running UN) {running UN = true; system. out. println ("beginning to finalize after" + created + "chairs have been created =>" + I);} if (I = 47) {system. out. println ("finalizing chair #47," + "setting flag to stop chair creation"); F = true ;} finalized ++; If (finalized> = created) system. out. println ("all" + finalized + "finalized ");}}

 

Public class garbagec {public static void main (string [] ARGs) {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); string themethstring = "after"; if (themethstring. equals ("before") {system. out. println ("GC ():"); system. GC (); system. out. println ("runfinalization ():"); system. runfinalization ();} system. out. println ("Bye! "); If (themethstring. Equals (" after ") system. runfinalizersonexit (true );}}

 

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.