Issue
I'm creating a small game where I would like to have a game room and a bunch of games in the game room. This would be a spring boot application. So I was thinking of starting the GameRoom at the start of the application. Then whenever a new game is created, I will add it to the list of games in the game roon. Is is a good idea? Or are there any potential pitfalls.
public class GameRoon{
private static GameRoom instance = null;
List<Game> games = new ArrayList();
private GameRoom() {}
public static GameRoom getIsntance() {
if(instance == null) {
instance = new GameRoom();
}
return instance;
}
}
The above is my unfinished singleton.. I have 2 questions. 1. Is it a good idea to start this during spring-boot start up? 2. Is it better to use singleton like this in spring-boot or is there a better way to do it
Solution
Singletons are highly debated and you will always find reasons for using it and for not.
In my opinion if your class responsibility is to hold a state (think of a registry with some data) which is shared within the application I don't see any problem. It is clear that you share the data and must be sure to govern concurrent access.
The main drawback of Singleton is testing: you have a global state but ideally during unit testing you want to test some code without relying on the singleton class (instead a mock). You can still solve this thanks to Spring: define the GameRoom as Spring bean (default scope is Singleton) which is injected like any other bean. This allows to mock it during unit testing, even if underneath there is a singleton behavior.
Answered By - Beppe C
Answer Checked By - Pedro (JavaFixing Volunteer)