请帮我检查下面的代码,如果Car-object被GC破坏,我想恢复程序逻辑,根据惯例,我的代码是否正确?
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();
答案 0 :(得分:2)
你所要求的并不是很清楚(正如专家所说)。但是代码中存在一个错误。请参阅以下评论。
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
更正确的方法是(虽然不太干净)
Car car = mWeakReference.get();
if (car == null) {
car = new Car();
mWeakReference= new WeakReference<Car>(car);
}
car.run();
答案 1 :(得分:0)
不,弱引用可能会再次被破坏。相反,重用: 汽车车;参考,并运行,这样你有一个硬参考,它不能是GC&#39; d。