Weak references in Java

Source: Internet
Author: User

Strong references

StringBuffer buffer = new StringBuffer();

Normal object creation is this type, and as long as buffer exists, the object will not be recycled by GC. It can also cause some problems, such as: When you add a handle to a hashmap, they don't automatically clear the cache of a picture when they are saved.

Weak references

referencequeue<string> WRQ = new referencequeue<string> ();
weakreference<string> ws = new weakreference<string> (s2, WRQ);

A weak reference cannot prevent the GC from reclaiming the memory that its object points to, and all of the Times by Handle.get () returns NULL. There is a dedicated weakhashmap that prevents the collection of objects because of the presence of keys. Storage for collections

Soft references

referencequeue<string> SRQ = new referencequeue<string> ();
softreference<string> ss = new softreference<string> (s1, SRQ);

Only when the memory is not enough to be recycled in weak reference, does not cause oom, so it is suitable for caching

Phantom references

referencequeue<string> PRQ = new referencequeue<string> ();
phantomreference<string> PS = new phantomreference<string> (S3, PRQ);

WeakReference is to put the handle into the Rference Queue before the GC, which can theoretically be resurrected in finalized. Phantom reference will only be placed in the reference queue after the object is retracted

Can be used to flag when an object is destroyed, or to ensure that the object is not resurrected in GC.

Reference:

Http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html

Https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references

Http://my.oschina.net/sulliy/blog/482101

Weak references in Java

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.