sunjinbo sunjinbo - 4 months ago 10
Java Question

What is the general way to use WeakReference when object was destroyed?

Please help me check the below codes, if the Car-object was destroyed by GC, I want to recover the program logic, according to the common practice, are my codes correct?

Car car = new Car();
WeakReference<Car> mWeakReference = new WeakReference<Car>(car);
mWeakReference.get().run();
...
if (mWeakReference.get() == null) {
Car newCar = new Car();
mWeakReference= new WeakReference<Car>(newCar);
}
mWeakReference.get().run();

Answer

It's not super clear what you are asking (as specializt said). But there's a bug in the code. See the comments below.

if (mWeakReference.get() == null) {
    Car newCar = new Car();
    mWeakReference= new WeakReference<Car>(newCar);  //instance set on weakref
} // maybe GC runs here
mWeakReference.get().run(); //instance could be null

A more correct approach would be (not too clean though)

Car car = mWeakReference.get();
if (car == null) {
    car = new Car();
    mWeakReference= new WeakReference<Car>(car);
} 
car.run();
Comments