I have a small app that has a Render thread. All this thread does is draw my objects at their current location.
I have some code like:
public void render() { // ... rendering various objects if (mouseBall != null) mouseBall.draw() }
Then I also have some mouse handler that creates and sets mouseBall to a new ball when the user clicks the mouse. The user can then drag the mouse around and the ball will follow where the mouse goes. When the user releases the ball I have another mouse event that sets mouseBall = null.
The problem is, my render loop is running fast enough that at random times the conditional (mouseBall != null) will return true, but in that split second after that point the user will let go of the mouse and I’ll get a nullpointer exception for attempting .draw() on a null object.
What is the solution to a problem like this?
The problem lies in the fact that you are accessing
mouseBalltwice, once to check whether it is notnulland another to call a function on it. You can avoid this problem by using a temporary like this: