0

I've recently run into a problem with my code, I have 1 thread executing and running the game, and another thread checking for all events that may have been called in the event:

Example of an Event:

       try {
            if (currentMinigame != null) {
            //Longer code and method execution time would usually be here, 
            //but for the sake of simplicity, I'll just use this
                currentMinigame.onEntityShootBow(e);
            }
        } catch (Exception ex) {
            exitEarly(ex);
        }

The problem is that, at some point, the thread executing the minigame will set currentMinigame to null. At which point, a null pointer will be called on the line: currentMinigame.onEntityShootBow(e);

Is there an easy way of synchronizing ALL of these events? (There are about 25 of them)

I thought of using Object currentMinigameLock = new Object(); Synchronized(currentMinigameLock) and putting this through each and every event, but every time I use synchronize; I almost never see a change, and that's a serious amount of code to refactor! Would there be an easier way?

Thanks Guys! -Tom

Thomas Nairn
  • 1,186
  • 8
  • 34
  • have you tried using the `volatile` key word? http://stackoverflow.com/questions/2423622/volatile-vs-static-in-java i dont know if that would fix it – chancea Jul 16 '13 at 15:49
  • I haven't actually, correct me if I'm wrong but, the minigame being set to null is actually an intended function as in - The minigame is no longer available. Wouldn't Volatile cause an error if set to null? I'm open to any changes with this :) – Thomas Nairn Jul 16 '13 at 15:51
  • @chancea I learnt what volatile actually does. Stupid considering I really should know that. But I don't really understand how volatile would fix this issue ? – Thomas Nairn Jul 16 '13 at 15:58
  • making the variable `volatile` and `synchronized` should mean that each thread will access it directly from the main memory and so as soon as the game thread makes it `null` the other one will instantly see that change. However I am still unsure of the rare case where its set to null after the `currentMinigame != null` check but before the `currentMinigame.onEntityShootBow(e)` – chancea Jul 16 '13 at 16:05

0 Answers0