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 especial
Some of the other answers seem incomplete or overly long. Here is a general answer.
You can do the following steps:
WeakReference variableMyClass has a weak reference to AnotherClass.
public class MyClass {
// 1. Create a WeakReference variable
private WeakReference 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);
}
}
MyClass was A and AnotherClass was B.WeakReference is to have another class implement an interface. This is done in the Listener/Observer Pattern.