Deep understanding of Weakhashmap

Source: Internet
Author: User
Tags java reference

Weakhashmap

(a) to view the API documentation, theweakhashmap points are as follows:

1. Hash table-based MAP implemented with weak keys. In Weakhashmap, when a key is no longer in normal use , its entry is automatically removed. More precisely, for a given key, the presence of its mapping does not prevent the garbage collector from discarding the key, which makes the key a terminating, terminated, and then recycled. When a key is discarded, its entry is effectively removed from the map

2. The behavior of the Weakhashmap class depends partly on the action of the garbage collector. Because the garbage collector can discard keys at any time, Weakhashmap is like an unknown thread that has been silently removed from the entry. In particular, even if the Weakhashmap instance is synchronized and no assignment method is called, the size method may return a smaller value after some time, for the IsEmpty method, return False, and then return true for the given key, ContainsKey The method returns true and then returns FALSE, the Get method returns a value for the given key, but then returns null for the key that previously appeared in the map, the Put method returns null, and the Remove method returns false for key set, value collection, and entry Set checks, the number of elements generated is decreasing.

3. Each key object in the Weakhashmap is stored indirectly as an indication object of a weak reference. Therefore, the key is removed automatically, either within the map or outside the map, only after the garbage collector clears the weak reference for a key.

(ii) Four categories of reference objects:

The API image is as follows:

1. Strong references (strong Reference)

2. Weak references (Weak Reference)

3. Soft Reference (Soft Reference)

4. Phantom references (Phantom Reference)

(iii) in- depth Understanding

At this point, there is a basic concept for weakhashmap, but it is still relatively vague. Find an English document that summarizes the main points below (if translation is not correct, please indicate, thank you):

1. Strong references

A strong reference is an ordinary Java reference, code:

    1. StringBuffer buffer = new StringBuffer ();

This code creates a StringBuffer object that stores a strong reference to the object in the variable buffer. Strong references are called "strong" (strong) because they interact with the garbage collector (garbage collector). In particular (specifically), if an object is connected by a strong reference (strongly reachable-a strong reference can be reached), then it is not processed in the garbage collection period. When you are using an object and do not want it to be destroyed by the garbage collection period, the strong reference usually fits exactly what you want.

2. When strong references are too strong

Suppose you want to use a final class widget, but for some reason you cannot inherit (extend) This class or add some new functionality to the class by other means. If you need to track the serial number of different objects of this class. You can then put these objects into HashMap and get different value values so that you can track the objects with different value values. Code:

    1. Serialnumbermap.put (widgets, Widgetserialnumber);

But a strong reference to the widget can create some problems. When we don't need a widget's serial number, we need to remove the widget's entry from HashMap. Otherwise we might face a memory leak (leak) (if we don't remove it when we should remove widgt), or we'll somehow lose the serial number (if we're removing it when we are using the widget). If these problems are similar, then these issues are a problem for developers of programming languages that have no garbage collection mechanism (non-garbage-collected language). Java developers do not need to worry about this kind of problem.

W : If an object has a strong reference, it is similar to essential necessities, and the garbage collector will never recycle it. When There is insufficientmemory space, theJava virtual machine prefers to throw a outofmemoryerror Error, which causes the program to terminate abnormally. You will not be able to easily reclaim objects with strong references to resolve out-of-memory issues.

Another common problem with strong references is image caching (cache). A normal strong reference will cause the image to continue to be stored in memory. In some cases, we do not need some images to remain in memory, we need to move them out of memory, we will play the garbage collection period role to determine which photos are removed. Causes these moved images to be destroyed by the garbage collector. Next time you're forced to play the garbage collection again, manually decide which image is recycled.

Note: I think I can also use the object's Hashcode to track the object. The authors cite this example only in the description of strong Reference.

3. Weak references

Simply put, a weak reference is not sufficient to force the object it is connected to persist in memory. A weak reference can affect the reachable level of an object in the (leverage) garbage collector. Code:

    1. weakreference<widget> weakwidget = new weakreference<widget> (Widget);

You can use the Weakwidget.get () method to get the actual strong reference object old. However, after that, it is possible to suddenly return a null value (if there is no other strong reference above the widget) because the weak reference is recycled. The packaged widgets are also recycled.

The simplest way to solve the problem with widget serial numbers is to use Weakhashmap. Its key value is a weak reference. If a Weakhashmap key becomes garbage, then it is automatically removed from the value of the app.

W : The garbage collection period does not always find a weak reference the first time, but it will be searched several times to find it.

4. Reference Queue (Reference quene)

Once a weak reference returns a null value, the object it points to (that is, the widget) becomes garbage, and the weakly referenced object (that is, weakwidget) is useless. This usually means cleaning up (cleanup) in a certain way. For example, Weakhashmap will remove some of the dead (dread) entry and avoid having too many weak references to die.

Referencequene can easily track down these dead weak references. It can be said that the referencequene passed into the Weakhashmap constructor (constructor), so that once the weak reference point to the object becomes garbage, the weak reference will be added to Referencequene.

As shown in the following:

5. Soft References

Soft references are basically the same as weak references, except for the urgency of throwing the object that you are pointing to. An object is weakly reachable (or a strong reference to the object is a weak reference object-the weak reference encapsulation of a strong reference), and the object will be discarded within a garbage collection loop. However, weak reference objects are retained for a period of time before they are discarded.

There is no difference between the execution of soft references and weak references. However, in the case of sufficient supply (in plentiful supply), the soft reachable object will be kept in memory for as long as possible. This allows them to have an excellent base of existence in memory (that is, the basis for the longest possible existence). Because you let the garbage collector worry about two things, one is the accessibility of this object, and one is how much the garbage collection period wants the memory that these objects are consuming.

6. Phantom references (Phantom Reference)

Phantom references are different from weak and soft references. It controls that the object it points to is very weak (tenuous) so that it cannot get the object. The get () method typically returns a null value. Its only function is to track the dead objects that are queued in the referencequene.

The difference between a phantom reference and a weak reference is the way in which the queue (Enquene) enters Referencequene. When the weakly referenced object becomes reachable, the weak reference is queued into referencequene. This queue occurs before the end (Finialize) and garbage collection actually occurs. Theoretically, the object of being garbage can be revived (resurrected) through the irregular (unorthodox) finilize () method, but the weak reference is still dead. Phantom references are queued only when the object is physically moved out of memory. This prevents us from re-restoring the object that will die.

W: End (finalization) refers to a more general concept of rubbish recycling, which can reclaim arbitrary resources that the object occupies, such as file descriptors and graphics contexts.

Phantom references are made up of two benefits:

A: It is the only way to determine when an object is removed from memory. Typically, this is not very useful. But sooner or later (come in handy) uses the case of manual processing of large pictures: If you're sure that a picture needs to be garbage collected, you should wait for the photo to be recycled before you try to load the next photo. This makes the dreaded (dreaded) memory overflow unlikely to occur.

B: The fundamental problem of the unreal reference being able to avoid the end (finilize). The Finilize () method can be resurrected by associating a strong reference to a garbage object. The problem is that objects that overwrite the Finilize () method have to perform two separate loops for recycling before they become garbage. The first round of loops determines that an object is garbage, and it conforms to the condition of terminating finilize. This object may be "resurrected" during the finilize process. The garbage collection period has to be rerun before the object is actually removed. Because Finilization is not called in real time, multiple loops of the GC may occur during termination. This leads to some delay lag when actually cleaning up the garbage objects. This causes a large amount of garbage in the heap to cause a memory overflow.

Phantom references cannot happen above, and when the Phantom reference is queued, it has actually been removed from memory. Phantom memory cannot "revive" the object. When this object is found to be unreal, it is recycled in the first round of the loop.

It can be proved that the Finilize () method is never used in the first case, but unreal references provide a more secure and efficient mechanism for using and removing the Finilize method, making garbage collection easier. But because there are so many things to do, I usually don't use finilize.

The relevant contents of the W:object class are as follows:

The relevant contents of this document are as follows:

(iv) original address and other translations

Original address: http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html

Other translation address: http://blog.csdn.net/fancyerii/article/details/5610360

This article is from the "Little New column" blog, please be sure to keep this source http://mikewang.blog.51cto.com/3826268/880775

Deep understanding of Weakhashmap

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.