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();
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); // 软引用
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); // 重新构建 }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor