I want to save an object (my game’s model/data) to disk, but as the game can get quite large – feasibly large enough to take several game ticks to store – I’m thinking it makes sense to perform the saving in a separate thread in order to keep the game running relatively smoothly.
What is the best method to achieve this? I wasn’t sure if it made sense to make the GameState (the model) a runnable or an extension of Thread, because most of the time it isn’t intended to be Runnable – logically, then, it shouldn’t be Runnable?
Other possibilities I’ve looked at are to have a Runnable GameSaver class, to which I pass the GameState or a copy of the GameState. Presumably, however, this would cause problems with synchronisation if I pass the GameState or will slow the game down while the class is cloned.
What’s the best approach, or the pro’s and con’s of approaches? Any other alternatives appreciated, too – I doubt my search has been exhaustive.
From a pure thread management perspective, the cleanest way I think is to use an executor. That does not solve your cloning (or not) issue.
Create a method that saves the game:
Create a runnable, as a class instance member for example, that embeds that call and an executor service:
And save the game as and when needed:
Don’t forget to shutdown the executor when closing your app:
You can also use a
ScheduledExecutorServiceinstead that runs every x minutes for example.The class might look like this for example:
and in your main code: