In Java, although the programmer does not need to manually manually manage the life cycle of the object, if you want some objects to have a certain life cycle (such as the insufficient memory, JVM will automatically recover certain objects to avoid the error of OutofMemory)) Soft references and weak references need to be used.
Starting from Java SE2, there are four types of references: strong reference, soft reference, weak reference and virtual use. There are two main purposes provided in Java to provide these four types of references: the first is to allow programmers to determine the life cycle of certain objects by code; the second is to benefit JVM for garbage recycling. Let’s explain the concepts of these four types:
References are divided into four, from high to low levels are based on thisstrong quotation–soft reference–weak reference–# 引#.
-
Quote Type
category recycling mechanism Survival time strong reference never recycled Object status jvm stopped running soft reference Recycling when memory is insufficient # Insufficient memory Weak quotation Object is recycled when not cited cache GC after running 虚 When the object is recycled
Management control precise memory stability unknown
strong reference
Never recover.
strong reference is common in the program code, similar toObject obj = new Object()
The references, as long as the reference still exists, the garbage collector will never recover the reference object.
weak reference (soft reference)
Focus on recycling objects.
Weak references are also used to describe non -necessary objects. Objects that are associated with weak references can only survive until the next garbage collection.
soft reference
Memory will be recycled when it is overflowing.
soft reference is used to describe some objects that are useful but not necessary. For a soft reference object, before the system is going to have abnormal memory overflow, these object lists will be recovered in the scope of the recycling range of these objects. If there is not enough memory this time, the memory overflow is thrown abnormal.
3 引 3 (Phantom Reference)
virtual quotation, also known as ghost quotation or phantom quoting, is the weakest relationship. Whether an object has a virtual reference will not affect its survival time at all, nor can it be obtained by obtaining an object instance through the use of virtual quotation. The only purpose of setting up the association for an object is to receive a system notification when this object is recycled by the collector.
Commonly used weak references and soft references
For example, in the picture loading framework, the memory cache is achieved by weak references.
// Implementation of the class of asynchronous loading of the picture
Public Class Asyncimageloader
{{
// Taking URL as the key, softReference as a value, create a cache hashmap key value pair.
Private Map <string, SoftReference <Drawable >> MIMAGECACHE =
New HashMap <string, SoftReference <Drawable >> ();
// Implement the picture asynchronous load
Public Drawable Loaddrawable (Final String ImageUrl, Final ImageCallback Callback)
{{
// Query the cache, see if the picture you need to download is in the cache
If (MIMAGECACHE.CONTAINSKEY (Imageurl))
{{
SoftReference <drawable> Softreference = MIMAGECACACHE.GET (Imageurl);
if (softReference.get ()! = NULL)
{{
RETURN SOFTREFERENCET ();
}
}
final handler handler = new handler ()
{{
@Override
Public Void DispatchMessage (MESSAGE MSG)
{{
// Return the ImageLoad method in ImageCallBackimpl and execute in the main line (UI thread).
callback.imageload (drawable msg.obj);
}
};
/*If not in the cache, open a new thread for downloading pictures from the Internet,
* Then send the obtained Drawable to the handler for processing, and implement the obtained picture displayed in the UI thread by callback
*/
New Thread ()
{{
public void run ()
{{
Drawable drawable = LoadimageFromurl (Imageurl);
// Stay the obtained picture in the cache
MIMAGECACHE.PUT (ImageUrl, New Softreference <Drawable> (DRAWABLE));
Message message = handler.obtainmessage (0, drawable);
handler.sendmessage (message);
};
} .start ();
// If there is no existence in the cache, after downloading the display from the Internet, return here;
Return null;
}
// Define a callback interface
Public Interface ImageCallback
{{
void Imageload (drawable drawable);
}
// Get the picture DRAWABLE object from the Internet through the URL;
ProteCTD DRAWALLOADIMAGEFROMURL (String Imageurl)
{{
try {
Return drawable.createFromStream (new url (imageurl) .opeenstream (), "debug");
} Catch (Exception E) {
// todo: handle exception
Throw New Runtimeexception (E);
}
}
}
Handler weakly reference to prevent memory leakage
public class MainActivity extends AppCompatActivity {
private Handler handler ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new MyHandler( this ) ;
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage( 0 ) ;
}
}).start() ;
}
private static class MyHandler extends Handler {
WeakReference<MainActivity> weakReference ;
public MyHandler(MainActivity activity ){
weakReference = new WeakReference<MainActivity>( activity) ;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if ( weakReference.get() != null ){
// update android ui
}
}
}
}