Danny Wilson
Danny Wilson

Reputation: 332

NullPointerException whilst learning concurrency in Scala

I'm having a little problem at the moment. My latest assignment is to create a rock paper scissors program which will run concurrently and output various values. Sounds simple and trivial, I know, but a little fun and I have been allowed to use scala which I had no knowledge of so thought it would be interesting.

Now the error is confusing me. I am receiving a NullPointerException on Thread 10, and have spent an awful long time trying to find it to no success. I have 6 classes so it would be impractical of me to put all of the code in, but I will put a few snippets.

result = Shapes.Winner(player1.getChoice(), player2.getChoice())

This is the line giving the error. Player1 and Player2 are simply objects from a class I have made, and they have been dequeued in.

Now for the confusing part. If I add a simple line in another class:

println(wait.getChoice())

it all works. This line has no relation to the first line above, and was simply for testing. But now when I take it out, I get the error. I would just leave it, but as you can see, it prints a load of rubbish onto the terminal.

I really have no idea what I'm doing wrong, and would love some help.

Feel free to ask for more snippets of the code, and thank you in advance for any help.

Upvotes: 0

Views: 199

Answers (1)

vitalii
vitalii

Reputation: 3365

The problem is that you use synchronized incorrectly. You should wrap all calls to Referee.queue into Referee.synchronized {} blocks in order to synchronization to work. Otherwise the calls are not synchronized, and it's possible for one thread to modify Referee.queue without other thread notice.

Otherwise you should use thread safe collection. For example when I substitute scala.collection.mutable.Queue with scala.collection.mutable.SynchronizedQueue in the Referee class everything works ok, and you don't need to synchronize access to queue. Even better use java.util.concurrent.ConcurrentLinkedQueue instead, because SynchronizedQueue is deprecated in scala_2.11

Upvotes: 1

Related Questions