Server/Server/src/main/java/uulm/teamname/marvelous/server/lobbymanager/LobbyRunner.java

77 lines
2.5 KiB
Java

package uulm.teamname.marvelous.server.lobbymanager;
import org.tinylog.Logger;
import uulm.teamname.marvelous.server.Server;
import java.util.HashMap;
/**
* Class meant for running lobbies. It manages said lobbies, creates threads for it, and moves it into an executor
*/
public class LobbyRunner {
private static boolean synchronous = false;
private static LobbyRunner instance;
static LobbyRunner getInstance() {
if (instance == null) {
instance = new LobbyRunner();
}
return instance;
}
private final HashMap<LobbyConnection, Thread> activeLobbies = new HashMap<>();
boolean canAddLobby() {
return activeLobbies.size() < Server.getMaxLobbies();
}
/** Starts a new thread for the current LobbyConnection, and adds it to the currently active lobbies */
void startLobby(LobbyConnection connection) {
Logger.trace("Starting lobby connection thread '{}'", connection.gameID);
synchronized (activeLobbies) {
if (activeLobbies.containsKey(connection)) {
Logger.warn("Already active lobby was started again. This is probably a bug.");
} else {
if(!synchronous) {
Logger.trace("Executing LobbyThread 'Lobby-{}'...", connection.gameID);
Thread lobbyThread = new Thread(connection, "Lobby-" + connection.gameID);
activeLobbies.put(connection, lobbyThread);
lobbyThread.start();
}else {
Logger.trace("Executing Lobby 'Lobby-{}'...", connection.gameID);
connection.runSynchronous();
}
}
}
}
void removeLobby(LobbyConnection lobby) {
synchronized (activeLobbies) {
if (!activeLobbies.containsKey(lobby)) {
Logger.warn("Tried to remove non-existent lobby thread. This is probably a bug.");
} else {
Logger.debug("Stopping and removing lobby '{}'", lobby.gameID);
activeLobbies.remove(lobby);
}
}
}
boolean isStarted(LobbyConnection connection) {
return activeLobbies.containsKey(connection);
}
/** Shutdown all threads, destroy the lobbies, and close everything up */
void shutdownAll() {
Logger.info("Stopping and removing all LobbyThreads");
activeLobbies.keySet().forEach(LobbyConnection::terminate);
Logger.debug("All lobby shutdown flags set");
}
// later...
void checkThreads() {
}
}