android:软引用/弱引用示例

发布于 2024-11-18 00:10:06 字数 213 浏览 2 评论 0原文

我的应用程序收到 OutOfMemoryError 错误。当我浏览一些教程时,我开始知道,我可以使用Softreference/Weakreference来解决这个问题。但我不知道如何使用Softreference/Weakreference

请向我推荐一些提供软引用或弱引用示例的教程。

谢谢...

I am getting OutOfMemoryError on my application. When i went through some tutorials, i came to know that, I can solve this issue by using Softreference/Weakreference. But I don't know that how to use Softreference/Weakreference.

Please suggest me some tutorials that providing examples for the Softreference or Weakreference.

Thank you...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

倾听心声的旋律 2024-11-25 00:10:06
package com.myapp;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.WeakHashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;


public class BitmapSoftRefrences {


      public static String SDPATH = Environment.getExternalStorageDirectory()
        + "/MYAPP";

// 1. create a cache map
public static WeakHashMap<String, SoftReference<Bitmap>> mCache = new WeakHashMap<String, SoftReference<Bitmap>>();
public static String TAG = "BitmapSoftRefrences";

// 2. ask for bitmap
public static Bitmap get(String key) {
    if (key == null) {
        return null;
    }

    try {
        if (mCache.containsKey(key)) {

            SoftReference<Bitmap> reference = mCache.get(key);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                return bitmap;
            }
            return decodeFile(key);
        }

    } catch (Exception e) {
        // TODO: handle exception
        Logger.debug(BitmapSoftRefrences.class,
                "EXCEPTION: " + e.getMessage());

    }

    // the key does not exists so it could be that the
    // file is not downloaded or decoded yet...

    File file = new File(SDPATH + "/" + key);

    if (file.exists()) {
        return decodeFile(key);
    } else {
        Logger.debug(BitmapSoftRefrences.class, "RuntimeException");

        throw new RuntimeException("RuntimeException!");
    }
}

// 3. the decode file will return bitmap if bitmap is not cached
public static Bitmap decodeFile(String key) {
    // --- prevent scaling
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inScaled = false;

    Bitmap bitmap = BitmapFactory.decodeFile(SDPATH + "/" + key, opt);

    mCache.put(key, new SoftReference<Bitmap>(bitmap));

    return bitmap;
}

public static void clear() {
    mCache.clear();
}

}
package com.myapp;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.WeakHashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;


public class BitmapSoftRefrences {


      public static String SDPATH = Environment.getExternalStorageDirectory()
        + "/MYAPP";

// 1. create a cache map
public static WeakHashMap<String, SoftReference<Bitmap>> mCache = new WeakHashMap<String, SoftReference<Bitmap>>();
public static String TAG = "BitmapSoftRefrences";

// 2. ask for bitmap
public static Bitmap get(String key) {
    if (key == null) {
        return null;
    }

    try {
        if (mCache.containsKey(key)) {

            SoftReference<Bitmap> reference = mCache.get(key);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                return bitmap;
            }
            return decodeFile(key);
        }

    } catch (Exception e) {
        // TODO: handle exception
        Logger.debug(BitmapSoftRefrences.class,
                "EXCEPTION: " + e.getMessage());

    }

    // the key does not exists so it could be that the
    // file is not downloaded or decoded yet...

    File file = new File(SDPATH + "/" + key);

    if (file.exists()) {
        return decodeFile(key);
    } else {
        Logger.debug(BitmapSoftRefrences.class, "RuntimeException");

        throw new RuntimeException("RuntimeException!");
    }
}

// 3. the decode file will return bitmap if bitmap is not cached
public static Bitmap decodeFile(String key) {
    // --- prevent scaling
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inScaled = false;

    Bitmap bitmap = BitmapFactory.decodeFile(SDPATH + "/" + key, opt);

    mCache.put(key, new SoftReference<Bitmap>(bitmap));

    return bitmap;
}

public static void clear() {
    mCache.clear();
}

}
唠甜嗑 2024-11-25 00:10:06

要创建 WeakReference,语法为 WeakReferencemyWeakReference = new WeakReference(actualObject);。要通过该 WeakReference 检索对象,请执行检查 if (weakWidget == null)。这样,如果已经被垃圾收集,您将避免 NullPointerException。

Ethan Nicholas 撰写的这篇 Java.net 文章 解释了为什么你想要使用WeakReference而不是强引用。它提供了名为 Widgetfinal(不可扩展)类的示例,该类没有定义串行 UID,假设开发人员决定定义一个串行 UID 来跟踪每个 小部件实例。他们通过创建一个新的HashMap并执行诸如serialNumberMap.put(widget, widgetSerialNumber);之类的操作来实现这一点,这是一个强引用。这意味着当不再需要它时必须明确清理它。开发人员有责任确切地知道何时手动“垃圾收集”该引用并将其从 HashMap 中删除,只有当他们确实确定它是时才应该这样做不再需要了。这可能是您在应用程序中遇到的问题。

在这种特殊情况下,正如文章所解释的,开发人员可以改用 Wea​​kHashMap 类(如 @NayAneshGupte 在他的示例中所说),其中键实际上是 WeakReference。这将允许 JVM 在其认为合适的情况下取消旧 Widget 的键,以便垃圾收集器可以出现并销毁其关联的对象。

文章还继续讨论了 SoftReferences 和 PhantomReferences(我从未使用过)。您可以在 这篇 javapapers.com 文章 和 < a href="http://www.rallydev.com/community/engineering/java-references-strong-soft-weak-phantom" rel="nofollow">此 Rally 博客。

To create a WeakReference, the syntax is WeakReference<SomeType> myWeakReference = new WeakReference<SomeType>(actualObject);. To retrieve the object via that WeakReference, do the check if (weakWidget == null). That way, you will avoid a NullPointerException if it has been garbage-collected already.

This Java.net article by Ethan Nicholas explains why you would want to use a WeakReference instead of a strong one. It provides the example of a final (unextendible) class called Widget that has no defined serial UID, presuming that the developer decides to define a serial UID to track each Widget instance. They do so by creating a new HashMap and doing something like serialNumberMap.put(widget, widgetSerialNumber); which is a strong reference. That means it must be explicitly cleaned up when no longer needed. The developer is responsible for knowing exactly when to manually "garbage-collect" that reference and remove it from the HashMap, which should be done only when they're really sure it's not needed anymore. This may be the problem you ran into in your application.

In this particular case, as the article explains, the developer could use the WeakHashMap class instead (as @NayAneshGupte put in his example), wherein the key is actually a WeakReference. This would allow the JVM nullify the keys to old Widgets as it saw fit, so that the garbage collector could come along and destroy their associated objects.

The article also goes on to talk about SoftReferences and PhantomReferences (which I've never used). You can read more about all of these in this javapapers.com article and this Rally blog.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文