Four common references in Java

Source: Internet
Author: User
Tags java reference

I. Java garbage collection mechanism

The Java garbage collector is responsible for completing three tasks:

1. allocate memory
2. Ensure that the memory of the referenced object is not recycled incorrectly.
3. Reclaim the memory space of objects that are no longer referenced

Garbage collection is a complex and time-consuming operation. If the JVM (Java Virtual Machine) spends too much time on garbage collection, it will inevitably affect the running performance of the application. Generally, when the Garbage Collector recycles an application, the execution of the entire application is temporarily suspended (STOP-the-world. This is because the Garbage Collector needs to update the actual memory address referenced by all objects in the application.

Different hardware platforms support different garbage collection methods. For example, on a multi-CPU platform, garbage collection can be performed in parallel. A single CPU platform can only be used in serial mode. Different applications may expect different garbage collection methods. The server-side application may wish to spend less time on garbage collection during the entire running time of the application, the better. For applications that interact with users, it is possible that the interval between application pauses caused by garbage collection is smaller, the better. JVM (Java Virtual Machine) provides a variety of garbage collection methods and corresponding performance optimization parameters for different situations. Applications can be customized as needed.

The most basic method of Java garbage collection mechanism is generational collection. The memory area is divided into different generations, and objects are stored in the corresponding generation region according to their survival time. Generally, it is divided into three generations: young, old, and permanent. Memory Allocation occurs in the young generation. When an object remains long enough, it will be copied to the old generation. Different garbage collection algorithms can be used for different generations. The starting point of generational recovery is the statistical law obtained after studying the object survival time in the application. In general, the survival time of most objects in an application is very short. For example, the survival time of local variables is only in the method execution process. Based on this, the garbage collection algorithm of the young generation can be very targeted.

The memory area of the young generation is further divided into Eden and two living vor zones ). The Eden area is the place where memory is allocated and a continuous idle memory area. The above memory allocation speed is very fast, because you do not need to find available memory blocks. One of the two vor zones is always blank. During garbage collection, objects that are still alive in the Eden and one of the non-empty primary vor areas are copied to the blank primary vor area or the old generation based on their survival time. After this copy, the previous non-empty movie vor area contains the currently alive objects, and the content in the Eden area and another movie vor area is no longer needed, simply clear the two regions. During the next garbage collection, roles in the two vor zones are exchanged. Generally, the young generation region is small, and most objects are no longer alive. Therefore, it is more efficient to search for surviving objects.

For the memory area of the old and permanent generations, different recycling algorithms are used, called the Mark-sweep-compact method. The marking process is to find and mark the currently alive objects. The clearing process is to traverse the entire memory area and find the areas to be recycled; compression moves the memory of the surviving object to one end of the entire memory area, making the other end a continuous idle area for convenient memory allocation and replication.

Java provides four different garbage collection mechanisms. The most common method is serial collection, that is, using a single CPU to reclaim memory for young and old generations. During the recycle process, the application is temporarily suspended. The recycling method is the most basic generational recycling mentioned above. The serial recycling method is suitable for a Single-CPU desktop platform. If it is a multi-CPU platform, it is suitable for parallel recovery. In this way, multiple CPUs are used for parallel processing when the young generation is recycled, which can improve the recovery performance. The concurrent tag-clear collection method is suitable for scenarios with high response time requirements for applications, that is, the temporary suspension time of applications caused by garbage collection needs to be reduced. The advantage of this method is that it can mark the alive object and recycle garbage while the application is running, but it only needs to suspend the application for a short time.

 

Ii. Java reference type

If an object in the memory has no reference, it indicates that the object is no longer in use and can become a candidate for garbage collection. However, the running time of the garbage collector is unknown, so the actual recycling time of objects that can be recycled is unknown. For an object, as long as there is a reference, it will always exist in the memory. If more and more such objects exceed the total JVM memory, the JVM will throw an outofmemory error.

Although the specific running of garbage collection is controlled by JVM, developers can still interact with the garbage collector to a certain extent, the purpose is to better help the Garbage Collector manage the application memory.

In Java, object references are divided into four levels, so that the program can control the object lifecycle more flexibly. The four levels are from high to low: strong reference, soft reference, weak reference, and virtual reference.
1) strong reference type

In general Java programs, strong reference is the most commonly seen ). For example, the most common code

// Variable definition string STR = "Hello wolrd"; object OBJ = new object (); Date = new date (),

In the code above, STR, OBJ, and date are strongly referenced objects. Strong references of objects can be passed everywhere in programs. In many cases, multiple references point to the same object. The existence of strong references limits the lifetime of objects in the memory. If object A contains a strong reference of object B, the survival time of object B is generally not shorter than that of object. If object A does not explicitly set the reference of object B to null, object B no longer directs to object a only after object A is reclaimed by garbage collection, to obtain the opportunity for garbage collection.

2) soft reference type

Soft reference is less powerful than soft reference, which is expressed by softreference class. Its function is to tell the Garbage Collector which objects in the program are not so important and can be recycled temporarily when the memory is insufficient. When the memory in the JVM is insufficient, the garbage collector will release the objects pointed to by soft references. If the memory is insufficient after all these objects are released, the out of memory error will be thrown.

Soft references are ideal for creating caches. When the system memory is insufficient, the content in the cache can be released. For example, if you consider an image editor program, it will read all the content of the image file into the memory for easy processing, and you can open multiple files at the same time. When too many files are opened at the same time, the memory may be insufficient. If soft references are used to point to the image file content, the garbage collector can reclaim the memory when necessary.

The following Java code shows how to use the soft reference type.

Public class bitmapcache {private string URL; // image URL private softreference <bitmap> softref; /// soft reference-the public bitmapcache (string URL) {This is released only when the system memory is insufficient. url = URL; softref = new softreference <bitmap> (null);} private bitmap loadremotebitmap () {final defaulthttpclient client = new defaulthttpclient (); final httpget getrequest = new httpget (URL); httpresponse response = client.exe cute (getrequest); Final int statuscode = response. getstatusline (). getstatuscode (); Final httpentity entity = response. getentity (); inputstream = entity. getcontent (); Final bytearrayoutputstream datastream = new bytearrayoutputstream (); outputstream = new bufferedoutputstream (datastream, io_buffer_size); copy (inputstream, outputstream); outputstream. flush (); Final byte [] DATA = datastream. tobytearray (); Final Bitmap bitmap = bitmapfactory. decodebytearray (data, 0, Data. length); Return bitmap;} public bitmap get Bitmap () {Bitmap bitmap = softref. get (); If (Bitmap = NULL) {// when the system memory is insufficient, the image has been released and you need to reload the network image bitmap = loadremotebitmap (); softref = new softreference <bitmap> (Bitmap) ;}return bitmap ;}}

When using the above program, because the objects pointed to by the soft reference may be recycled, when the get method is used to obtain the objects actually pointed to by the soft reference, always check whether the object is still alive.

3) Weak reference type

Weak reference is weaker than soft reference in strength and is represented by the weakreference class. It references an object but does not prevent the object from being recycled. If a strong reference is used, as long as the reference exists, the referenced object cannot be recycled, and the weak reference does not. When the garbage collector is running, if all references of an object are weak references, the object will be recycled. Weak references are used to solve the coupling relationship between objects brought about by strong references on the survival time.

Weak references are most commonly used in collection classes, especially in hash tables. The hash table interface allows any Java object as the key ). When a key-value pair is put into a hash table, the hash table object itself has reference to these key-value objects. If this type of reference is strongly referenced, as long as the hash table object itself is still alive, the key and value objects contained in it will not be recycled. If a long-lived hash table contains many key-value pairs, it may eventually consume all the memory in the JVM. The solution to this problem is to use weak references to reference these objects, so that the key and value objects in the hash table can be recycled by the garbage collector in a timely manner. The weakhashmap class can be used in Java to meet this common requirement.

4) Virtual Reference Type

Before introducing virtual references, you should first understand the object termination mechanism (finalization) provided by Java ).

There is a Finalize method in the object class. Its original design is that it can be used to perform some cleanup before an object is actually recycled. Because Java does not provide a mechanism similar to the C ++ destructor, it is simply implemented through the Finalize method. However, the problem is that the running time of the garbage collector is not fixed, so the actual running time of these cleanup tasks is unpredictable.

You can use phantom reference to solve this problem. You must specify a reference queue when creating a virtual reference phantomreference. When the Finalize method of an object has been called, the virtual reference of this object will be added to the queue. Check the content in the queue to see if an object is ready to be recycled.

The usage of virtual references and their queues is rare. It is mainly used to implement fine-grained memory usage control, which makes sense for mobile devices. The program can apply for memory to create a new object after determining that an object is to be recycled. In this way, the memory consumed by the program can be maintained in a relatively low amount.

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.