What is weakhashmap--turn

Source: Internet
Author: User

Original address:http://laravel.iteye.com/blog/2303244

Where in the world is Java weakhashmap Weak, is it really weak? What are the weakhashmap scenarios and what should be noticed when using them? What are the different effects of weak and strong references on Java GC? This article will give a clear and concise introduction.

General Introduction

At the end of the Java Collection Framework series article, the author intends to introduce a special member:Weakhashmap, which can be seen from a name as a Map. What makes it special is that the weakhashmap entry may be automatically deleted by the GC, even if the programmer does not have a call remove() or clear() method.

More intuitively, when using weakhashmap , even if no elements are added or removed that are displayed, the following can occur:

  • Call two size() methods to return different values;
  • Two call isEmpty() method, first return false , second return true ;
  • Two call containsKey() methods, first return true , second return false , although two use the same key ;
  • Two calls the get() method, returns one for the first time, value returns the second time, null although two times the same object is used.

Encounter such a wonderful phenomenon, do you think users will be crazy? In fact,this feature ofWeekhashmap is especially useful for scenarios where caching is required . In the cache scenario, all objects cannot be cached because memory is limited, and object cache hits can improve system efficiency, but the cache miss does not cause errors because it can be computed again.

To understand how Weekhashmap works, you also need to introduce a concept: weak references (weakreference). We all know that the memory in Java is automatically managed by GC, and the GC automatically determines which objects can be reclaimed when the program is running and frees the memory at the right time. The GC determines whether an object can be recycled based on whether there is a valid reference to the object . If there is no valid reference to the object (basically means that there is no way to access the object), then the object is recyclable. The "Valid references" here do not include weak references . That is, although a weak reference can be used to access an object, a weak reference is not taken into account when it is garbage collected, and only objects with weak references will still be recycled by GC .

Weakhashmap Internal is managed by weak references entry , what does the weak reference attribute mean to weakhashmap ? Putting a pair into key, value a weakhashmap does not prevent the key value from being reclaimed by GC unless there is a key strong reference to it outside of Weakhashmap .

The concepts of strong references, weak references, etc. are explained later, and it is only necessary to know that the references in Java are of a different kind, and that different kinds of references will have a difference in the GC effect.

Specific implementation

WEAKHASHMAP storage structure is similar to HashMap, readers can refer to the previous article, which is not mentioned here.

As for the management of strong and weak references, the blogger will explain the topic separately.

Weak HashSet?

If you have seen the previous several explanations of Map and Set , will ask: since there are weekhashmap, whether there is weekhashset it? The answer is no: (. However, the Java Collections Tool class gives a solution to Collections.newSetFromMap(Map<E,Boolean> map) wrap any Map into a set. A Weak HashSetcan be quickly obtained by:

Wrap the Weakhashmap into a set
set<object> Weakhashset = Collections.newsetfrommap (
New Weakhashmap<object, boolean> ());

Not what you expected, the newSetFromMap() method just made a simple wrapper over the incoming Map :

Collections.newsetfrommap () is used to wrap any map into a set
public static <E> set<e> Newsetfrommap (map<e, boolean> Map) {
return new setfrommap<> (map);
}

private static class Setfrommap<e> extends Abstractset<e>
Implements Set<e>, Serializable
{
Private final map<e, boolean> m; The backing map
private transient set<e> s; Its keySet
Setfrommap (Map<e, boolean> Map) {
if (!map.isempty ())
throw new IllegalArgumentException ("Map is Non-empty");
m = map;
s = Map.keyset ();
}
public void Clear () {m.clear ();}
public int size () {return m.size ();}
public Boolean isEmpty () {return m.isempty ();}
Public Boolean contains (Object o) {return m.containskey (o);}
public boolean remove (Object o) {return m.remove (o) = null;}
Public boolean Add (e e) {return M.put (E, boolean.true) = = null;}
Public iterator<e> Iterator () {return s.iterator ();}
Public object[] ToArray () {return S.toarray ();}
Public <T> t[] ToArray (t[] a) {return S.toarray (a);}
Public String toString () {return s.tostring ();}
public int hashcode () {return S.hashcode ();}
public boolean equals (Object o) {return o = = This | | s.equals (o);}
public boolean Containsall (collection<?> c) {return s.containsall (c);}
public boolean RemoveAll (collection<?> c) {return s.removeall (c);}
public boolean Retainall (collection<?> c) {return s.retainall (c);}
AddAll is the only inherited implementation

}

What is weakhashmap--turn

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.