I'm making a Java multi-player turn-based game and I want to limit the time that each player have to make their move, the game is composed of game sessions or rooms and each room have 4 players. The game have around 40 game sessions and each sessions have a minimum of 160 turns.
First I looked into the java.util.Timer
, then I found out about the ScheduledExecutorService
which seems much better, I could have a SingleThreadScheduledExecutor
for each game session, create a new runnable each turn and if the player make is move before the runnable is executed I could call the ScheduledFuture.cancel()
method.
In theory it seems fine but I have some concerns, so I want to know if:
Is this the right approach? or there are better alternatives?
Could I just have a ScheduledThreadPool
for all game sessions instead
one SingleThreadScheduledExecutor
for each game session?
I noticed that canceling a ScheduledFuture
will keep it in the
memory until his execution time, could this be a problem for the
memory usage?
And last, is it possible to reuse the same runnable (1 for each game session) instead of creating a new one each turn.
A ScheduledExecutorService
is a fine place to start. Just remember to properly synchronize your access to game state.
It is generally legal to recycle a runnable, but that is probably not the best option here.
Unless the number of turns were going to be huge, the overhead for cancelling tasks is not worth it. Instead, include in your runnable information on what turn in what game is being timed. When the task executes, check the game state to see if that is still the current turn, and do nothing if the turn count has already moved on.
This avoids race conditions between cancel()
completing and the task executing, as would happen when a move is submitted close to the deadline.