Home >Java >Javagetting Started >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!