MicroEyes
MicroEyes

Reputation: 3742

Losing object reference when accessing data from different thread

I apologize to write the whole bunch of code, but couldn't find words to explain my issue.

Issue: GameHandler creates object of GameData and passed this as ITraceble. GameData object has a reference of ITraceable object. GameTask implementes Runnable, so its going to run on a different thread. But when i try to call m_gameData.traceMeNow() from anywhere inside of GameTask, I am getting m_game.m_traceable as null.

public interface ITraceable {
     public void trace(String a_args);
}

public class GameData {
     ITraceable m_traceable;
     public GameData(ITraceable a_traceable) {
         m_traceable = a_traceable;
     }

     public void traceMeNow() {
         m_traceable.trace("something to trace");    <----- m_traceable ref is NULL.
     }
}

public class GameTask implements Runnable {
    GameData m_gameData;
    public GameTask(GameData a_gameData) {
        m_gameData = a_gameData;
        m_gameData.traceMeNow();                <---Function call from here
    }

    public void run() {
       //something here
    }
}

class GameHandler implements ITraceable {
    public void trace(String a_args) {
         //writting some logs here.
     }

    public void createObjects() {               < ------ Creating objects here
        GameData l_gameData = new GameData(this);
        GameTask l_gameTask = new GameTask(l_gameData);
        //--- Starting GameTask in other Thread ----// 
    }    
}

Upvotes: 1

Views: 285

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

Declare the variable final:

final ITraceable m_traceable;

This guarantees that all threads will see the assigned value (provided the reference to this isn't unsafely published in the constructor, which it is not here).

Upvotes: 1

Related Questions