I'm writing a game in Java where each game object has a number of properties, but these can all be changed in one of two ways:

  • Every second, a tick runs which may automatically cause a change.
  • Users can send a request to the server and make a modification themselves.

Should I lock the Object while the tick is running, or is this not beneficial? I was just concerned, for example, if the user made a change to an object while the tick was deleting it.

  • 1
    You need to synchronize access to shared mutable state. If there are multiple threads that can access the same instance of a mutable object, you need to ensure that they all get to see a consistent state. – Hulk Jun 26 '16 at 8:40
  • What is the point of this tick? Does it exist to resolve synchronization issues like this modification or some other reason? – candied_orange Jun 26 '16 at 10:38
  • Hi Candied, it's a game, and a tick is ran every second to do things like add more money to your account and randomly trigger events to happen which will change different properties. – Oliver Dunk Jun 26 '16 at 10:39
  • 1
    Not what I asked. You may have a grab bag of things that happen during the tick. I'm asking if anything changes outside of this tick. Some games are turn based like that. You have yet to define your game that clearly. – candied_orange Jun 26 '16 at 10:42
  • 1
    queue all changes and process them one by one. – downrep_nation Jun 26 '16 at 16:49

Whenever two or more threads need to change the same object and potentially at the same time, you need to ensure that the object remains in a consistent state making it synchronized.

Apparently, it's not only about the object, but also its containing object, because you mention "if the user made a change to an object while the tick was deleting it".


Another approach could be to implement object update requests by using the command design pattern. You could then maintain a shared queue of commands that would be fed by the web server and by the tick. You could then consume the queue in a single update thread executing one command at a time, thus avoiding conflicts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.