|
@@ -18,12 +18,7 @@ public class RoomService {
|
|
|
|
|
|
private static RoomService instance;
|
|
|
/** 房间对象池 **/
|
|
|
- public Queue<Room> roomPool;
|
|
|
- /** 最大空闲房间数量 **/
|
|
|
- private int maxIdleRooms;
|
|
|
- /** 房间清理线程 **/
|
|
|
- private ScheduledExecutorService cleaner;
|
|
|
-
|
|
|
+ public RoomPool roomPool;
|
|
|
/** 房间缓存 [key:房间类型, value:房间实例] **/
|
|
|
public Map<Integer, Room> roomMap = new ConcurrentHashMap<>();
|
|
|
|
|
@@ -41,61 +36,7 @@ public class RoomService {
|
|
|
*/
|
|
|
public void init(int maxIdleRooms) {
|
|
|
logger.info("初始化房间服务...");
|
|
|
- this.roomPool = new ConcurrentLinkedQueue<>();
|
|
|
- this.maxIdleRooms = maxIdleRooms;
|
|
|
- this.cleaner = Executors.newSingleThreadScheduledExecutor();
|
|
|
- // 定期清理空闲房间
|
|
|
- this.cleaner.scheduleAtFixedRate(this::cleanIdleRooms, 10, 30, TimeUnit.SECONDS);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 获取房间对象
|
|
|
- *
|
|
|
- * @param roomType
|
|
|
- * @return
|
|
|
- */
|
|
|
- public Room acquireRoom(int roomType) {
|
|
|
- Room room = this.roomPool.poll();
|
|
|
- if (room == null) {
|
|
|
- // 创建指定类型的房间
|
|
|
- room = RoomFactory.createRoom(roomType);
|
|
|
- }
|
|
|
- return room;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 归还房间对象
|
|
|
- */
|
|
|
- public void releaseRoom(Room room) {
|
|
|
- if (room != null) {
|
|
|
- this.roomPool.offer(room); // 放回池中
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 定期清理空闲房间
|
|
|
- */
|
|
|
- private void cleanIdleRooms() {
|
|
|
- while (this.roomPool.size() > maxIdleRooms) {
|
|
|
- Room room = this.roomPool.poll();
|
|
|
- if (room != null) {
|
|
|
- // 销毁房间,释放资源
|
|
|
- room.destroy();
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 关闭对象池
|
|
|
- */
|
|
|
- public void shutdown() {
|
|
|
- this.cleaner.shutdownNow();
|
|
|
- this.roomPool.forEach(Room::destroy);
|
|
|
- this.roomPool.clear();
|
|
|
- }
|
|
|
-
|
|
|
- public int getAvailableRooms() {
|
|
|
- return this.roomPool.size();
|
|
|
+ this.roomPool = new RoomPool(maxIdleRooms);
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -154,7 +95,7 @@ public class RoomService {
|
|
|
*/
|
|
|
public Room creatRoom(Player player, int roomType, JSONObject jsonData) {
|
|
|
// 从对象池获取房间
|
|
|
- Room room = this.acquireRoom(roomType);
|
|
|
+ Room room = this.roomPool.acquireRoom(roomType);
|
|
|
// int roomId = this.randomRoomId();
|
|
|
synchronized (room) {
|
|
|
// 初始化房间
|