android------- strong reference, soft reference, weak reference, virtual reference use

In Java, although programmers do not need to manually manage the life cycle of objects, if you want some objects to have a certain life cycle (for example, when the memory is insufficient, the JVM will automatically recycle some objects to avoid OutOfMemory errors). Soft and weak references are used.

Since Java SE2, four types of references have been provided: strong references, soft references, weak references, and virtual references. There are two main purposes of providing these four reference types in Java: the first is to allow programmers to determine the life cycle of certain objects through code; the second is to facilitate garbage collection by the JVM. The concept of these four types of references is explained below:

 

References are divided into four, from high to low level, strong reference - soft reference - weak reference - virtual reference .

  • reference type

    category recycling mechanism use survival time
    strong citation never recycle object state When the JVM stops running
    soft reference Recycle when memory is low cache Not enough storage
    weak reference Recycled when the object is not referenced cache After GC runs
    phantom reference When the object is recycled Management Control Precise Memory Stability unknown


 

 

Strong references are
never recycled.
Strong references are ubiquitous in program code. Similar to Object obj = new Object()this type of reference, as long as the strong reference still exists, the garbage collector will never reclaim the referenced object.

 

Weak references (Soft Reference)
focus on recycling objects.
Weak references are also used to describe non-essential objects. Objects associated with weak references can only survive until the next garbage collection occurs.

 

Soft reference (Weak Reference)
memory will be reclaimed when it overflows.
Soft references are used to describe objects that are still useful but not required. For objects associated with soft references, the system will recycle these object lists in the recovery range before a memory overflow exception occurs. If there is not enough memory for this collection, an out-of-memory exception will be thrown.

 

Phantom Reference (Phantom Reference) Phantom
reference, also known as ghost reference or phantom reference, is the weakest reference relationship. Whether an object has a virtual reference will not affect its lifetime at all, and an object instance cannot be obtained through a virtual reference. The only purpose of setting a phantom reference association for an object is to receive a system notification when the object is reclaimed by the collector.

 

Commonly used weak and soft references

For example, in the image loading framework, memory caching is implemented through weak references.

//实现图片异步加载的类
public class AsyncImageLoader
{
    //以Url为键,SoftReference为值,建立缓存HashMap键值对。
    private Map<String, SoftReference<Drawable>> mImageCache =
        new HashMap<String, SoftReference<Drawable>>();
     
    //实现图片异步加载
    public Drawable loadDrawable(final String imageUrl, final ImageCallback callback)
    {
        //查询缓存,查看当前需要下载的图片是否在缓存中
        if(mImageCache.containsKey(imageUrl))
        {
            SoftReference<Drawable> softReference = mImageCache.get(imageUrl);
            if (softReference.get() != null)
            {
                return softReference.get();
            }
        }
         
        final Handler handler = new Handler()
        {
            @Override
            public void dispatchMessage(Message msg)
            {
                //回调ImageCallbackImpl中的imageLoad方法,在主线(UI线程)中执行。
                callback.imageLoad((Drawable)msg.obj);
            }
        };
         
        /*若缓存中没有,新开辟一个线程,用于进行从网络上下载图片,
         * 然后将获取到的Drawable发送到Handler中处理,通过回调实现在UI线程中显示获取的图片
         */
        new Thread()
        {      
            public void run()
            {
                Drawable drawable = loadImageFromUrl(imageUrl);
                //将得到的图片存放到缓存中
                mImageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            };
        }.start();
         
        //若缓存中不存在,将从网上下载显示完成后,此处返回null;
        return null;
         
    }
     
    //定义一个回调接口
    public interface ImageCallback
    {
        void imageLoad(Drawable drawable);
    }
     
    //通过Url从网上获取图片Drawable对象;
    protected Drawable loadImageFromUrl(String imageUrl)
    {
        try {
            return Drawable.createFromStream(new URL(imageUrl).openStream(),"debug");
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
}

Handler weak references to prevent memory leaks

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
            }
        }
    }
 
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325957460&siteId=291194637