How to use WeakReference in Java and Android development?

Viewed 102367

I have been a java developer for 2 years.

But I have never wrote a WeakReference in my code. How to use WeakReference to make my application more efficient especially the Android application?

4 Answers

Some of the other answers seem incomplete or overly long. Here is a general answer.

How to use WeakReference in Java and Android

You can do the following steps:

  1. Create a WeakReference variable
  2. Set the weak reference
  3. Use the weak reference

Code

MyClass has a weak reference to AnotherClass.

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.

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.
  • An alternative to using a WeakReference is to have another class implement an interface. This is done in the Listener/Observer Pattern.

Practical example

Related