alex
alex

Reputation: 5694

Java + Eclipse: False possible null pointer dereference?

I'm experiencing a warning in Eclipse regarding a "possible null pointer dereference" but i really don't get why. The warning occurs in the following code snippet in the last line:

public void addMessage(Message message) {
   WeakReference<MessagesPanelControl> view = null;
   [...]
   if(view != null && view.get() != null)
     view.get().updateView();
}

Because of the check before, i'am totally sure, that view can't be null. The Eclipse warning is:

Bug: Possible null pointer dereference in AC.GUI.MessageHandler.addMessage(Message) due to return value of called methodBug: Possible null pointer dereference in AC.GUI.MessageHandler.addMessage(Message) due to return value of called method

If its not a valid warning, how can i supress it? Even @SuppressWarnings("all") does not work.

Upvotes: 2

Views: 1667

Answers (2)

You have a race condition between your if statement and its body:

  • You check whether view is null. It's not.
  • You check whether view.get() (the weakly-referenced MessagesPanelControl) is null. It's not. You enter the if body.
  • The garbage collector decides to clear the value inside view.
  • You call a method on view.get(), which is now null.

To prevent this, you need to convert the weak reference into a strong reference like this:

if(view != null) {
    MessagesPanelControl mpc = view.get();
    if(mpc != null)
        mpc.updateView();
}

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1502546

You're assuming that just because view.get() returns a non-null value the first time, it will return a non-null value the second time. It may not - the target could be removed between the two calls. You could eliminate this with:

if (view != null) {
    MessagesPanelControl value = view.get();
    if (value != null) {
        value.updateView();
    }
}

Upvotes: 7

Related Questions