Home > Java > Javagetting Started > body text

Introduction to strong references and weak references in java

王林
Release: 2020-04-10 15:50:45
forward
2705 people have browsed it

Introduction to strong references and weak references in java

1. Strong reference

We usually create a new object and it is a strong reference. For example,

Object obj = new Object();
Copy after login

Even in the case of insufficient memory, the JVM would rather Throwing an OutOfMemory error will not reclaim such an object.

(Recommended video tutorial: java video tutorial)

2. Soft reference

If an object only has a soft reference, then the memory If there is enough space, the garbage collector will not reclaim it; if there is insufficient memory space, the memory of these objects will be reclaimed.

SoftReference<String> softRef=new SoftReference<String>(str);     // 软引用
Copy after login

Use:

Soft references have important applications in practice, such as the browser's back button. When you press back, will the content of the web page displayed when you go back be re-requested or fetched from the cache? This depends on the specific implementation strategy.

(1) If a webpage recycles its content at the end of browsing, you will need to rebuild it when you press Back to view the previously browsed page.

(2) If the browsed web pages are stored in the memory, it will cause a lot of waste of memory, and even cause memory overflow.

The following code:

Browser prev = new Browser();               // 获取页面进行浏览
SoftReference sr = new SoftReference(prev); // 浏览完毕后置为软引用        
if(sr.get()!=null){ 
    rev = (Browser) sr.get();           // 还没有被回收器回收,直接获取
}else{
    prev = new Browser();               // 由于内存吃紧,所以对软引用的对象回收了
    sr = new SoftReference(prev);       // 重新构建
}
Copy after login

Recommended related tutorials: javaQuick Start

The above is the detailed content of Introduction to strong references and weak references in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!