In the previous article on Java theory and practice, Brian Goetz, a Java cleaning engineer, explored weak references, which allows you to warn the Garbage Collector that you want to maintain a reference to an object, the object is not blocked from being garbage collected. In this article, he will explain another form of the reference object, soft references, to help the Garbage Collector manage memory usage and eliminate potential memory leaks.
Garbage collection prevents Memory leakage in Java programs, at least for the narrow definition of "Memory leakage", but this does not mean that we can completely ignore the object lifetime (lifetime) in Java programs) problem. When we do not pay enough attention to the object lifecycle (lifecycle) or break the standard mechanism for object lifecycle management, memory leakage usually occurs in Java programs. For example, the last time we saw that the lifecycle of objects cannot be divided, an unexpected object persistence occurs when attempting to associate metadata with a instantaneous object. In other cases, you can ignore or destroy object lifecycle management and cause memory leakage.
Free object
One form of Memory leakage is sometimes called object loitering, which is described by the leakychecksum class in Listing 1. There is a getfilechecksum () in Listing 1 () this method is used to calculate the file content checksum. The getfilechecksum () method reads the file content to the buffer to calculate the checksum. A more intuitive implementation simply allocates the buffer zone as a local variable in getfilechecksum (), but this version is more "smart" than that version ", instead of caching the buffer in the instance field to reduce the memory limit. This "optimization" usually does not bring about the expected benefits; the object distribution ratio is expected by many people to be cheaper. (Also note that it is no longer thread-safe to promote the buffer from the local variable to the instance variable so that the class does not have additional synchronization. The intuitive implementation does not need to declare getfilechecksum () as synchronized, and will provide better scalability during simultaneous calls .)
Listing 1. display the "object free" Class
// Bad code-do not emulate
Public class leakychecksum {
Private byte [] bytearray;
Public synchronized int getfilechecksum (string filename ){
Int Len = getfilesize (filename );
If (bytearray = NULL | bytearray. Length <Len)
Bytearray = new byte [Len];
Readfilecontents (filename, bytearray );
// Calculate checksum and return it
}
}
This class has many problems, but we focus on Memory leakage. The cache buffer decision is probably based on the assumption that the class will be called many times in a program, so it should be more effective to reuse the buffer instead of allocating it again. But the result is that the buffer will never be released because it is always reachable for the Program (unless the leakychecksum object is garbage collected ). Even worse, it can grow but cannot be reduced, so leakychecksum will permanently maintain a buffer with the same size as the maximum file being processed. Back to step 1, this will also put pressure on the garbage collector and require more frequent collection; maintaining a large buffer for future checksum calculation is not the most effective use of available memory.
The cause of the leakychecksum problem is that the buffer is logically local for the getfilechecksum () operation, but its lifecycle has been artificially extended because it is promoted to the instance field. Therefore, this class must manage its own buffer lifecycle? Instead of making JVM manage.
Soft reference
In the previous article, we saw how the weak reference can provide an application with another method to reach the object when the object is used by the program, but it does not extend the lifecycle of the object. Another subclass of reference ?? Soft reference ?? It can meet a different but related purpose. Weak references allow applications to create references that do not impede garbage collection. Soft references allow applications to use the help of the garbage collector by specifying objects as "expendable. Although the garbage collector does a good job of finding out which ones are used by the application and which ones are not used, determining the most appropriate use of available memory depends on the application. If the application makes a bad decision to keep the object, the performance will be affected because the Garbage Collector must work harder to prevent the application from consuming all the memory.
High-speed cache is a common performance optimization that allows applications to reuse previous computing results instead of re-computing. High-speed cache is a compromise between CPU utilization and memory usage. The ideal balance of this compromise depends on how much memory is available. If there are too few high-speed caches, the required performance advantages cannot be achieved. If there are too many caches, the performance will be affected because too much memory is used on the high-speed cache, as a result, insufficient memory is available for other purposes. Because the garbage collector is more suitable for determining memory requirements than the application, it is necessary to use the Garbage Collector to help with these decisions.
If the only remaining reference of an object is weak or soft reference, the object is soft (Softly reachable ). The garbage collector does not collect soft objects as much as possible as it collects weak objects. On the contrary, it collects soft objects only when the memory is actually "needed. Soft reference is a method for the garbage collector, that is, "as long as the memory is not very tight, I will keep this object. But if the memory gets really tight, I will collect and process this object ." The garbage collector needs to clear all soft references before it can throw an outofmemoryerror.
Using a soft reference to manage the cache buffer can solve the leakychecksum problem, as shown in Listing 2. Currently, as long as the memory is not especially needed, the buffer will be retained, but it can also be recycled by the garbage collector when needed:
Listing 2. Fix leakychecksum with soft reference
Public class cachingchecksum {
Private softreference <byte []> bufferref;
Public synchronized int getfilechecksum (string filename ){
Int Len = getfilesize (filename );
Byte [] bytearray = bufferref. Get ();
If (bytearray = NULL | bytearray. Length <Len ){
Bytearray = new byte [Len];
Bufferref. Set (bytearray );
}
Readfilecontents (filename, bytearray );
// Calculate checksum and return it
}
}
A cheap Cache
Cachingchecksum uses a soft reference to cache a single object and allows the JVM to process the details when the object is removed from the cache. Likewise, soft references are often used in GUI applications to cache bitmap images. The key to whether soft references can be used is whether applications can recover data from a large number of caches.
To Cache more than one object, you can use a map, but you can choose how to use soft references. You can manage the cache as Map <K, softreference <v> or softreference <Map <K, V>. The latter option is usually better, because it does less work for the garbage collector and allows the whole cache to be reclaimed with less work when memory is especially needed. Weak references are sometimes mistakenly used to replace soft references and build caches, but this results in poor cache performance. In practice, the weak reference will be quickly cleared after the object becomes weak and accessible ?? Usually before the cached object is used again ?? Because small garbage collection runs frequently.
For applications that rely heavily on high-speed caching in terms of performance, soft references are useless, it does not replace a complex high-speed cache framework that provides flexible end-to-end, replication, and transactional caching. But as a "cheap and dirty" high-speed cache mechanism, it is very attractive to reduce the price.
As with weak references, soft references can also be created as a reference queue with a reference, which is included when the reference is cleared by the garbage collector. Reference queues are not as useful as weak references for soft references, but they can be used to issue management alarms, indicating that the application is beginning to lack memory.
How does the Garbage Collector handle references?
Weak references and soft references both extend the abstract reference class (the same is true for phantom references), which will be introduced in future articles ). The referenced object is specially viewed by the garbage collector. When the Garbage Collector encounters a reference during the tracking heap, it does not mark or trace the reference object. Instead, it places a reference in the queue of known active reference objects. After tracking, the garbage collector recognizes soft objects ?? These objects have no strong references except soft references. What about the garbage collector ?? Determine whether soft reference needs to be cleared at this time based on the total amount of memory collected by the current collection and other policy considerations. Soft references to be cleared will enter the queue if there is a reference queue. The remaining soft and object (the object that has not been cleared) is then considered as a root set, and the heap trace continues to use these new roots, so that accessible objects can be marked through active soft references.
After processing soft references, the weak and object sets are identified ?? Such an object does not have a strong reference or soft reference. These objects are cleared and added to the queue. All reference types are cleared before they are added to the queue. Therefore, the thread that processes post-mortem cleanup never has access to the referent object, but only the access to the reference object. Therefore, when references are used together with the reference queue, you usually need to subdivide the appropriate reference type and apply it directly to your design (like weakhashmap, its map. the entry extends weakreference) or stores references to objects to be cleared.
Performance cost of reference Processing
Referencing objects brings additional costs to the garbage collection process. Each spam collection must construct a list of active reference objects, and each reference must be properly processed. This adds some reference overhead for each collection, regardless of whether the referent is collected at this time. The reference objects themselves are subject to garbage collection and can be collected before the referent, in which case they are not added to the queue.
Array-based collection
When an array is used to implement a data structure such as a stack or a circular buffer, another form of object separation occurs. The leakystack class in listing 3 shows the stack implementation implemented by arrays. In the POP () method, after the pointer on the top declines, elements will still retain references to the objects that will pop up the stack. This means that the reference of this object is still accessible to the Program (even if the program does not actually use this reference), this will prevent the object from being garbage collected, until this location is reused by the future push.
Listing 3. Object separation in an array-based set
Public class leakystack {
Private object [] elements = new object [max_elements];
Private int size = 0;
Public void push (Object O) {elements [size ++] = O ;}
Public object POP (){
If (size = 0)
Throw new emptystackexception ();
Else {
Object result = elements [-- size];
// Elements [size + 1] = NULL;
Return result;
}
}
}
In this case, the object is removed by removing its reference after the object pops up from the stack, as shown in the line commented out in listing 3. But what is this ?? Is the class managing its own memory ?? It is a rare situation, that is, it is a good idea to explicitly eliminate unnecessary objects. Most of the time, it is considered that the forcible elimination of references that should not be used will not bring about performance or memory usage gains, usually resulting in worse performance or nullpointerexception. This problem does not occur if one of the links of the algorithm is implemented. In the link implementation, the life cycle of the linked node (and the reference of the stored object) will be automatically bound with the period during which the object is stored in the collection. Weak references can be used to solve this problem ?? Maintain weak references instead of a strongly referenced array ?? However, in practice, leakystack manages its own memory, so it is responsible for ensuring that references to unwanted objects are cleared. Using arrays to implement stacks or buffers is a kind of optimization that can reduce allocation, but it will bring a greater burden to the implementers. You need to carefully manage the life cycle of references stored in arrays.
Conclusion
As with weak references, soft references help prevent application programs from getting rid of objects by using the Garbage Collector to make cache reclaim decisions. Soft references are applicable only when applications can tolerate a large number of soft referenced objects.
References:
For more information, see the original article on the developerworks global site.
"Java Theory and Practice: Blocking Memory leakage with weak references": This article introduces the similar weakreference of softreference in the previous Java theory and practice.
"Focus on performance: optimizing garbage collection": Kirk Pepperdine and Jack Shirazi demonstrated that even a slow memory leak will eventually put a lot of pressure on the garbage collector.
Reference objects and garbage collection: This article is from Sun, which describes how the Garbage Collector treats reference objects shortly after the reference object is added to the class library.
Java theory and practice: a complete series written by Brian Goetz.
Java Technology Zone: hundreds of articles on various aspects of Java programming.
Obtain products and technologies
Jtune: This Free jtune tool can leverage GC logs and display heap size, GC duration, and other useful memory management data in charts.