Search code examples
javaweak-references

Initialise WeakReference object to avoid null check


Given the below example code is there a way to initialise total such that I do not have to do a null check later when I use it. I am not able to pass the value into the constructor.

public class SampleCode 
{

    private WeakReference<Float> total;

    public SampleCode() {
    }

    public void setWidget(Float total) {
        this.total = new WeakReference<>(total);
    }

    public float calculatePercentage(Float count) {
        if (total == null) {
            return -1;
        }
        if (total.get() == null) {
            return -1;
        }

        return count / total.get();
    }
}

I would like to do something like this in the constructor:

this.total = new WeakReference<>(null);

But that doesn't work. Can I initialise a WeakReference in a released state or does that go against the classes purpose?

Thanks

Edit

Thanks for all the feedback.

  • The use of float was meant to simplify the question but I can completely understand the confusion. The object actually being held by the weak reference is a view in an Android layout and this class lives outside the activities lifecycle.
  • total.get() should be assigned to a local value before it is evaluated
  • The statement "This does not work" was in relation to:

total.get() == null evaluating to false after initialising with this.total = new WeakReference<>(null); I now understand that statement to be incorrect. This will evaluate to true. However I think it might be better to not initialise it to null and just check the null condition before access.


Solution

  • You can initialise it like this:

    private WeakReference<Float> total = new WeakReference<>(null);
    

    Now the reference itself will never be null, but it's get method does return null.
    Example of the new calculatePercentage method:

    public float calculatePercentage(Float count) {
        Float totalF = total.get();
        if(totalF == null)
            return -1;
    
        return count / totalF;
    }
    

    However,
    in most situations it makes very little sense to use a WeakReference<Float>. Why not just use the primitive float? Or if you really want to a Float object. Because when would the Float object really be garbage collected? I think it would only lead to inconsistent state and hard to track bugs.