简体   繁体   English

Java和Android开发中如何使用WeakReference?

[英]How to use WeakReference in Java and Android development?

I have been a java developer for 2 years.我已经做了 2 年的 Java 开发人员。

But I have never wrote a WeakReference in my code.但是我从来没有在我的代码中写过 WeakReference。 How to use WeakReference to make my application more efficient especially the Android application?如何使用 Wea​​kReference 使我的应用程序更高效,尤其是 Android 应用程序?

Using a WeakReference in Android isn't any different than using one in plain old Java.在 Android 中使用WeakReference与在普通的旧 Java 中使用WeakReference没有什么不同。

You should think about using one whenever you need a reference to an object, but you don't want that reference to protect the object from the garbage collector.当您需要对对象的引用时,您应该考虑使用一个,但您不希望该引用保护对象免受垃圾收集器的影响。 A classic example is a cache that you want to be garbage collected when memory usage gets too high (often implemented with WeakHashMap ).一个经典的例子是当内存使用率过高时你希望被垃圾收集的缓存(通常用WeakHashMap实现)。

Be sure to check out SoftReference and PhantomReference as well.请务必查看SoftReferencePhantomReference

EDIT: Tom has raised some concerns over implementing a cache with WeakHashMap .编辑: Tom 对使用WeakHashMap实现缓存提出了一些担忧。 Here is an article laying out the problems: WeakHashMap is not a cache!这是一篇阐述问题的文章: WeakHashMap 不是缓存!

Tom is right that there have been complaints about poor Netbeans performance due to WeakHashMap caching. Tom 是对的,有人抱怨由于WeakHashMap缓存导致 Netbeans 性能不佳。

I still think it would be a good learning experience to implement a cache with WeakHashMap and then compare it against your own hand-rolled cache implemented with SoftReference .我仍然认为使用WeakHashMap实现缓存然后将其与您自己使用SoftReference实现的手动缓存进行比较会是一个很好的学习体验。 In the real world, you probably wouldn't use either of these solutions, since it makes more sense to use a 3rd party library like Apache JCS .在现实世界中,您可能不会使用这些解决方案中的任何一个,因为使用Apache JCS 之类的 3rd 方库更有意义。

[EDIT2] I found another good example of WeakReference . [EDIT2]我发现了另一个WeakReference好例子。 Processing Bitmaps Off the UI Thread page in Displaying Bitmaps Efficiently training guide, shows one usage of WeakReference in AsyncTask.Displaying Bitmaps Efficiently培训指南中从 UI 线程页面处理位图显示了 AsyncTask 中WeakReference一种用法。

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private int data = 0;

    public BitmapWorkerTask(ImageView imageView) {
        // Use a WeakReference to ensure the ImageView can be garbage collected
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        data = params[0];
        return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
    }

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}

It says,它说,

The WeakReference to the ImageView ensures that the AsyncTask does not prevent the ImageView and anything it references from being garbage collected .对 ImageView 的 WeakReference 确保 AsyncTask 不会阻止 ImageView 及其引用的任何内容被垃圾收集 There's no guarantee the ImageView is still around when the task finishes, so you must also check the reference in onPostExecute().无法保证任务完成时 ImageView 仍然存在,因此您还必须检查 onPostExecute() 中的引用。 The ImageView may no longer exist, if for example, the user navigates away from the activity or if a configuration change happens before the task finishes. ImageView 可能不再存在,例如,如果用户导航离开活动或者在任务完成之前发生配置更改。

Happy coding!快乐编码!


[EDIT] I found a really good example of WeakReference from facebook-android-sdk . [编辑]我从facebook-android-sdk找到了一个非常好的WeakReference示例。 ToolTipPopup class is nothing but a simple widget class that shows tooltip above anchor view. ToolTipPopup类只不过是一个简单的小部件类,它在锚视图上方显示工具提示。 I captured a screenshot.我截取了屏幕截图。

美味的截图

The class is really simple(about 200 lines) and worthy to look at.这个类真的很简单(大约 200 行),值得一看。 In that class, WeakReference class is used to hold reference to anchor view, which makes perfect sense, because it makes possible for anchor view to be garbage collected even when a tooltip instance lives longer than its anchor view.在该类中, WeakReference类用于保存对锚视图的引用,这是非常有意义的,因为即使工具提示实例的寿命长于其锚视图,锚视图也可以被垃圾收集。

Happy coding!快乐编码! :) :)


Let me share one working example of WeakReference class.让我分享一个WeakReference类的工作示例。 It's a little code snippet from Android framework widget called AutoCompleteTextView .这是来自 Android 框架小部件的一小段代码片段,名为AutoCompleteTextView

In short, WeakReference class is used to hold View object to prevent memory leak in this example.简而言之, WeakReference类用于保存View对象,以防止本示例中的内存泄漏

I'll just copy-and-paste PopupDataSetObserver class, which is a nested class of AutoCompleteTextView .我将只复制并粘贴 PopupDataSetObserver 类,它是AutoCompleteTextView的嵌套类。 It's really simple and the comments explains the class well.这真的很简单,评论很好地解释了课程。 Happy coding!快乐编码! :) :)

    /**
     * Static inner listener that keeps a WeakReference to the actual AutoCompleteTextView.
     * <p>
     * This way, if adapter has a longer life span than the View, we won't leak the View, instead
     * we will just leak a small Observer with 1 field.
     */
    private static class PopupDataSetObserver extends DataSetObserver {
    private final WeakReference<AutoCompleteTextView> mViewReference;
    private PopupDataSetObserver(AutoCompleteTextView view) {
        mViewReference = new WeakReference<AutoCompleteTextView>(view);
    }
    @Override
    public void onChanged() {
        final AutoCompleteTextView textView = mViewReference.get();
        if (textView != null && textView.mAdapter != null) {
            // If the popup is not showing already, showing it will cause
            // the list of data set observers attached to the adapter to
            // change. We can't do it from here, because we are in the middle
            // of iterating through the list of observers.
            textView.post(updateRunnable);
        }
    }

    private final Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            final AutoCompleteTextView textView = mViewReference.get();
            if (textView == null) {
                return;
            }
            final ListAdapter adapter = textView.mAdapter;
            if (adapter == null) {
                return;
            }
            textView.updateDropDownForFilter(adapter.getCount());
        }
    };
}

And the PopupDataSetObserver is used in setting adapter. PopupDataSetObserver用于设置适配器。

    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
    if (mObserver == null) {
        mObserver = new PopupDataSetObserver(this);
    } else if (mAdapter != null) {
        mAdapter.unregisterDataSetObserver(mObserver);
    }
    mAdapter = adapter;
    if (mAdapter != null) {
        //noinspection unchecked
        mFilter = ((Filterable) mAdapter).getFilter();
        adapter.registerDataSetObserver(mObserver);
    } else {
        mFilter = null;
    }
    mPopup.setAdapter(mAdapter);
}

One last thing.最后一件事。 I also wanted to know working example of WeakReference in Android application, and I could find some samples in its official sample applications.我还想知道 Android 应用程序中WeakReference工作示例,我可以在其官方示例应用程序中找到一些示例。 But I really couldn't understand some of them's usage.但我真的无法理解其中的一些用法。 For example, ThreadSample and DisplayingBitmaps applications use WeakReference in its code, but after running several tests, I found out that the get() method never returns null , because referenced view object is recycled in adapters, rather then garbage collected.例如, ThreadSampleDisplayingBitmaps应用程序在其代码中使用WeakReference ,但在运行几次测试后,我发现 get() 方法从不返回null ,因为引用的视图对象在适配器中被回收,而不是垃圾收集。

Some of the other answers seem incomplete or overly long.其他一些答案似乎不完整或过长。 Here is a general answer.这是一个通用的答案。

How to use WeakReference in Java and Android如何在 Java 和 Android 中使用 Wea​​kReference

You can do the following steps:您可以执行以下步骤:

  1. Create a WeakReference variable创建一个WeakReference变量
  2. Set the weak reference设置弱引用
  3. Use the weak reference使用弱引用

Code代码

MyClass has a weak reference to AnotherClass . MyClassAnotherClass有一个弱引用。

public class MyClass {

    // 1. Create a WeakReference variable
    private WeakReference<AnotherClass> mAnotherClassReference;

    // 2. Set the weak reference (nothing special about the method name)
    void setWeakReference(AnotherClass anotherClass) {
        mAnotherClassReference = new WeakReference<>(anotherClass);
    }

    // 3. Use the weak reference
    void doSomething() {
        AnotherClass anotherClass = mAnotherClassReference.get();
        if (anotherClass == null) return;
        // do something with anotherClass
    }

}

AnotherClass has a strong reference to MyClass . AnotherClassMyClass有很强的引用。

public class AnotherClass {
    
    // strong reference
    MyClass mMyClass;
    
    // allow MyClass to get a weak reference to this class
    void someMethod() {
        mMyClass = new MyClass();
        mMyClass.setWeakReference(this);
    }
}

Notes笔记

  • The reason you need a weak reference is so that the Garbage Collector can dispose of the objects when they are no longer needed.您需要弱引用的原因是垃圾收集器可以在不再需要对象时处理它们。 If two objects retain a strong reference to each other, then they can't be garbage collected.如果两个对象彼此保持强引用,则它们不能被垃圾收集。 This is a memory leak.这是内存泄漏。
  • If two objects need to reference each other, object A (generally the shorter lived object) should have a weak reference to object B (generally the longer lived object), while B has a strong reference to A. In the example above, MyClass was A and AnotherClass was B.如果两个对象需要相互引用,对象 A(通常是寿命较短的对象)应该对对象 B(通常是寿命较长的对象)有一个弱引用,而 B 对 A 有一个强引用。在上面的例子中, MyClass是A 和AnotherClass是 B。
  • An alternative to using a WeakReference is to have another class implement an interface.使用WeakReference的替代方法是让另一个类实现一个接口。 This is done in the Listener/Observer Pattern .这是在Listener/Observer Pattern 中完成的

Practical example实际例子

A "canonicalized" mapping is where you keep one instance of the object in question in memory and all others look up that particular instance via pointers or somesuch mechanism. “规范化”映射是您将所讨论对象的一个​​实例保留在内存中,而所有其他实例通过指针或某种此类机制查找该特定实例。 This is where weaks references can help.这是弱引用可以提供帮助的地方。 The short answer is that WeakReference objects can be used to create pointers to objects in your system while still allowing those objects to be reclaimed by the garbage-collector once they pass out of scope.简短的回答是WeakReference对象可用于创建指向系统中对象的指针,同时仍然允许这些对象在超出范围时被垃圾收集器回收。 For example if I had code like this:例如,如果我有这样的代码:

class Registry {
     private Set registeredObjects = new HashSet();

     public void register(Object object) {
         registeredObjects.add( object );
     }
 }

Any object I register will never be reclaimed by the GC because there is a reference to it stored in the set of registeredObjects .我注册的任何对象都不会被GC回收,因为在registeredObjects集合中存储了对它的引用。 On the other hand if I do this:另一方面,如果我这样做:

class Registry {
     private Set registeredObjects = new HashSet();

     public void register(Object object) {
         registeredObjects.add( new WeakReference(object) );
     }
 }

Then when the GC wants to reclaim the objects in the Set it will be able to do so.然后当 GC 想要回收 Set 中的对象时,它将能够这样做。 You can use this technique for caching, cataloguing, etc. See below for references to much more in-depth discussions of GC and caching.您可以使用此技术进行缓存、编目等。有关 GC 和缓存的更深入讨论的参考,请参见下文。

Ref: Garbage collector and WeakReference参考:垃圾收集器和 WeakReference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM