Java reference summary [draft]

Source: Internet
Author: User

(Because recently write a small tool, in the mobile phone platform needs to use, so sorted out most of the relevant documents, hope to be useful to readers, if there is a written mistake please send a letter to tell Thank you: silentbalanceyh@126.com)

1. Java Garbage Collector Overview

The Java. Lang. Ref package is introduced in the Java2 Platform. Classes in this package allow us to reference objects, but these objects do not need to stay in the memory. In addition, these classes have some interactions with Java garbage collectors. We usually use the system. GC () method during development. What is the basic working principle of GC in Java? Of course, the main purpose of using the Java reference class is to have limited interaction with the Java garbage collector, thus comprehensively improving the memory management efficiency, this situation is more effective in embedded systems, real-time systems, and systems with strict memory requirements.

1) GC Principle

Java memory management mainly refers to the management of objects in the memory, including memory allocation and release operations for these objects, anyone who has learned Java knows Java's memory model. For a Java object, there are two types of storage: Memory heap ), the memory heap is unordered and mainly used to store the created Java objects. One is the memory stack, which is mainly used to store Java references and then points to the Java objects during the management process. GC is responsible for recycling objects when the objects are "inaccessible". Common statements include:

Object o = NULL;

But how does CG work? When the system creates an object, that is, when we use the new keyword to create an object, GC starts to monitor the object address, size, and usage status. Generally, Java's GC mechanism has specific collectionAlgorithmGC usually uses a directed graph to record all objects in the queue. In this way, it is used to determine which objects are "reachable" and which are "inaccessible ". When GC judges that some objects are not reachable, GC has the responsibility to reclaim the relevant memory space. However, because of platform differences, there are too many uncertainties when calling system. GC ().ProgramAfter system. GC () is called, only the program sends a request to the JVM. When does the JVM perform garbage collection? different platforms. (*: Do not think that after system. GC () is called, the garbage collector will recycle the system memory. The memory collected by the system depends on the platform and system .)

2) incremental GC (incrementalgc)

GC usually starts a new process or a group of new processes in JVM. It occupies heap space and CPU usage like Java User Programs. During GC design, the pause time and recovery rate must be weighed because it occupies heap. If GC runs too long, the user will feel that the Java program itself will have a certain pause. If the running time is too short, there will be a lot of memory not recycled, so that the Java objects created in the program occupy a lot of memory. The incremental GC method divides a long interrupt into many small interruptions through a certain collection algorithm, which reduces the impact of GC on the program itself. In fact, the overall performance of the incremental mode is not as high as normal, but it can reduce the pause time and improve the user experience. Of course, in addition to this method, the overall GC method is:

Reference counting collector );

Tracing Algorithm (tracing collector );

Compacting algorithm (compacting collector );

Copying algorithm (coping collector );

Generation Algorithm (generational collector );

Adaptive Algorithm (Adaptive collector );

For related algorithms, refer to relevant documents.

2. Object reference classification in Java

Object references in Java mainly include the following types:

1) strongly reachable ):

Objects that can be accessed through strong references. Generally, we usually writeCodeAre strongly referenced objects, such as the following code segment:

Stringbuilder builder = new stringbuilder ();

The reference to OBJ in the above Code references an object in the memory heap. In this case, as long as the OBJ reference exists, the garbage collector will never release the storage space of the object. This kind of object becomes strong references, which is the native Java reference of the Java language. We use it almost every day for programming. The above code JVM stores a strong reference of a stringbuilder type object in variable builder. The interaction between strong references and GC is like this. If an object is reachable through strong references or through strong reference chains, this object becomes highly accessible, in this case, the object Garbage Collector ignores it. If we do not need the Garbage Collector to recycle this object during the development process, we will directly assign this object as a pre-reference.

2) softly reachable ):

Objects with strong references cannot be accessed, that is, they are not highly accessible objects. However, objects that can be accessed through soft references become soft accessible objects, software and Objects Require softreference (Java. lang. ref. softreference ). This type of reference is mainly used for memory-sensitive high-speed cache, and this type of reference still has a strong reference function. When the memory is insufficient, GC will reclaim this type of memory, therefore, when the memory is sufficient, such references will not be recycled. Not only that, this reference object ensures that it is set to null before the outofmemory exception is thrown in the JVM. Generally speaking, this type of reference ensures that the JVM memory is fully understood when the JVM memory is insufficient, but the key is: whether the Garbage Collector releases software and objects at runtime is uncertain, in addition, the garbage collection algorithm cannot guarantee that all soft and accessible objects can be found at one time. When the garbage collector is running, it can freely release the memory that is not strong enough to occupy the object. If the garbage collector finds the soft and object, it may perform the following operations:

[1] set the referent field of the softreference object to null so that the object does not reference the heap object.

[2] All objects on the memory stack referenced by softreference will be finalizable.

[3] When the finalize () method of the object on the memory stack is run and the memory occupied by the object is released, the softreference object will be added to its referencequeue, the precondition is that referencequeue exists.

Since such an object exists in Java, how can we create such an object when writing code? The procedure is as follows:

First, create an object, use the normal reference method [strong reference], then create a softreference to reference this object, and finally set the normal reference to null. In this way, this object only retains a softreference reference. In this case, the created object is the softreference object. In general, we can use this reference to complete the cache function, that is, the front side is used for high-speed cache, to ensure maximum use of memory without causing memory leakage. The following code segment:

Public static void main (string ARGs [])

{

// Create a strongly accessible object

A A = new ();

// Create a soft reference softreference for this object

Softreference sr = new softreference ();

// Set strong references to null and clear strong references by the Garbage Collector

A = NULL;

// The next operation to use this object

If (SR! = NULL ){

A = (a) Sr. Get ();

} Else {

// This is because the memory is too low and soft reference has been released, so you need to reload it once.

A = new ();

Sr = new softreference ();

}

}

The soft reference technology enables the java system to better manage memory, maintain system stability, prevent memory leakage, and avoid system crashes, therefore, this technology can be used to process objects with large memory usage and long lifecycles.

3) weakly reachable ):

Neither strong or object nor soft or object. weakreference (Java. lang. ref. weakreference). This type of object is used for canonicalized mapping. It is also useful for objects with a long life cycle and a low overhead during re-creation, different from soft reference objects, the garbage collector releases the weakreference object memory if it encounters a weak object. However, the garbage collector needs to run many times to find the weak object. When a weak reference object is used, it can be used with the referencequeue class. If the weak reference is recycled, JVM adds the weak reference to the relevant reference queue. The simplest weak reference method is as follows:

Weakreference weakwidget = new weakreference (classa );

In the above Code, when weakwidget. Get () is used to obtain the classa, because the weak reference itself cannot prevent garbage collection, we may get a null value and return it. [*: Here is a tip. If we want to obtain information about an object without affecting the garbage collection process, we can use weakreference to remember this object, generally, we use this method when developing the debugger and optimizer.]

If the above code is used, we use weakwidget. if get () returns NULL, it indicates that the object has been recycled by the garbage collector. In this case, the weak reference object loses its use value, and GC defines it as needing to be cleared. In this case, weak references cannot reference any object, so it becomes a dead reference in JVM, which is why we sometimes need to use the referencequeue class together, after referencequeue is used, it makes it easier for us to monitor the referenced object. If we construct a reference object through a referencequeue class, when the referenced object has been recycled, the system will automatically use the object reference queue to replace object reference. We can use the referencequeue class to determine whether to actually clear the dead reference from the garbage collector.

Weak reference code segment:

// Create a common reference object

Myobject object = new myobject ();

// Create a reference queue

Referencequeue RQ = new referencequeue ();

// Use the reference queue to create a weak reference of myobject

Weakreference wR = new weakreference (object, rq );

Here we provide two real scenarios to describe the usage of weak references:

(1) If you want to append some information to an object, you can use hashtable to associate the object with the additional information. You keep putting objects and additional information into hashtable, but when the object is used up, you have to remove the object from hashtable. Otherwise, the memory occupied by the object will not be released. If you forget it, the objects not removed from hashtable can also be counted as memory leaks. The ideal situation is that when the object is used up, the object in hashtable will be automatically reclaimed by the garbage collector, or you are doing garbage collection.

(2) You want to implement an image cache because the cost of loading images is relatively high. You can cache the reference of an image object so that you can reuse it later. However, you must determine which images in the cache are no longer needed and remove the references from the cache. No matter what Cache Management Algorithm you use, you are actually working on garbage collection and a simpler approach (unless you have special requirements, this should also be the best way) is to let the Garbage Collector handle, it determines which object to recycle.

When the Java recycler encounters a weak reference, it may perform the following operations:

[1] set the referent field of the weakreference object to null so that the object does not reference the heap object.

[2] all objects in the memory stack referenced by weakreference will be finalizable.

[3] When the finalize () method of the object on the memory stack is run and the memory occupied by the object is released, the weakreference object will be added to its referencequeue, the precondition is that referencequeue exists.

4) clear:

When the referent field of the referenced object is set to null and the object referenced by the reference class in the memory heap is declared as final, the object can be cleared.

5) phantomly reachable ):

It is not a strong or object, nor a soft or object. It is also not a weak or object. The reason why virtual or object can be put to the end is mainly because of its particularity, sometimes we call it a "ghost object". If it has ended, it can be accessed through virtual quotes. We use the class phantomreference (Java. Lang. Ref. phantomreference) for access. This class can only be used to track the collection of referenced objects. Likewise, it can be used to perform the per-mortern clearing operation. Phantomreference must be used with the referencequeue class. The referencequeue must be used because it can act as a notification mechanism. When the Garbage Collector determines that an object is virtual and accessible, the phantomreference object is placed on its referencequeue, this is a notification, indicating that the object referenced by phantomreference has ended and can be collected. Generally, this action is taken just before the object is recycled. This type of reference is different from weak reference and soft reference. The get () object always returns NULL, only when these objects are in the referencequeue queue, we can know which objects it references are dead references ). The difference between such a reference and a weak reference is:

Weakreference enters the referencequeue queue as soon as possible when the object is inaccessible. It does occur before the finalization method is executed and garbage collection, theoretically, this type of object is incorrect, but the weakreference object can continue to be in the dead state,

Phantomreference is a referencequeue queue that enters after the object has been removed from the physical memory. The get () method always returns NULL.

When the Garbage Collector encounters a virtual reference, it is possible to perform the following operations:

[1] The heap object referenced by phantomreference is declared as finalizable;

[2] It is added to its referencequeue before the heap object is released. In this case, we can take the action before the heap object is recycled (*: Remind again, the phantomreference object must be created through the Associated referencequeue, that is, it must be operated with the referencequeue class)

What is the purpose of a seemingly useless virtual reference?

1. First, we can use virtual references to know when the object is actually removed from the memory, and this is the only way.

2. virtual references avoid the finalize () method, because for execution of this method, the objects actually referenced by virtual references are abnormal objects. If you want to use objects in this method, you can only recreate them. Generally, the garbage collector polls twice, marks it as finalization at a time, and recycles it for the second time. However, it often does not support real-time tagging, or garbage collection will wait for an object to mark finalization. This situation is likely to cause memoryout, and the use of virtual references will completely avoid this situation. Because the process of using a false reference to reference an object does not make the object revived by dead, and such an object can be recycled during the recycling period.

In JVM, virtual references are more secure and effective than the finalize () method. The finaliaze () method is relatively simple to implement in the virtual machine, and can also handle most of the work, so we still use this method to perform the object recycling operation, however, with virtual references, you can choose whether to manually operate the object to make the program more efficient and perfect.

3. lifecycle of objects in Java

In the JVM runtime space, the entire object declaration cycle is roughly divided into the following stages:

Creating-> using-> invisible-> unreachable-> collected) -> finalized-> free)

[1] creation stage:

The creation process takes several steps:

Allocate memory space for objects

Start Object Construction

Recursively call the constructor of superclasses

Object instance initialization and variable Initialization

Execution Constructor

[2] features of the application phase:

The system maintains at least one strong reference of the object)

All references to this object are strong references, unless we have declared soft references, weak references, or virtual references.

[3] not depending on the stage:

The invisible stage means that we cannot reference it in the region code, that is, the strong reference has disappeared. In general, we set the object at this time to null, the main purpose is to enable JVM to discover it and reclaim the resources occupied by this object in a timely manner.

[4] inaccessibility phase:

Objects in the inaccessibility phase cannot be directly or indirectly referenced in the object reference root SET managed by the virtual machine, these objects usually refer to the temporary variables and references in all thread stacks. These objects are all objects to be recycled, but they cannot be directly recycled by GC.

[5] collection, termination, and release phases:

Objects in the last stage of the object lifecycle may be in three states:

The garbage collector finds that the object is no longer reachable.

The Finalize method has been executed.

The object has been reused.

4. Conclusion:

I have sorted out the content about object reference in the whole Java, basically covering most of the content, if there is a mistake to read the letter to inform: silentbalanceyh@126.com.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/silentbalanceyh/archive/2009/08/21/4468368.aspx

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.