I've been building a simple rock, paper, scissors game that's played between two server clients for a college lab. I have a very simple server that starts the game when two clients have signed on. It works like this:
The server creates a game object and waits for player clients to ask for a game.
Once two players request a game the server creates a player 1 object and a player 2 object, passing the game object into their constructors.
The players call methods on the player objects which in turn call methods on game object. The game object has synchronized methods in it.
Each player makes their move, which is stored in the game object, then the game object calculates the winner.
The player objects call the same methods in the game object, this all works fine. But a friend of mine was puzzled by the fact I don't call wait() or notify() in any of my methods. He has already presented his lab, and passed. He asked about wait() and notify() within a synchronized method but he said her response was vague and he still isn't sure, but I should probably put them in just in case. So what's the deal?? Do I need wait() and notify() in a synchronized method?
Also, I read that synchronized doesn't work between Java virtual machines, is this true? If so, how does this affect my game, is synchronized doing anything at all??
Many thanks.
wait() and notify() are a mechanism for explicit communication between threads within a single JVM. To vastly oversimplify, wait() means something like "It's your turn", and notify() means "OK, I'm done." You never need to add them "just to be safe" -- the idea is absolutely preposterous, in fact.
The synchronized keyword is mainly used to ensure that all threads see the same, valid view of shared data; the problem that it's meant to solve can't come up between separate JVMs, so the fact that it does nothing in that case is fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With