|
@@ -5,7 +5,6 @@ import com.incubator.game.player.Player;
|
|
|
import org.slf4j.Logger;
|
|
|
|
|
|
import java.util.Map;
|
|
|
-import java.util.Queue;
|
|
|
import java.util.concurrent.*;
|
|
|
|
|
|
/**
|
|
@@ -16,13 +15,8 @@ public class ContestService {
|
|
|
protected Logger logger = Log4jUtil.getLogger(getClass());
|
|
|
|
|
|
private static ContestService instance;
|
|
|
- /** 官方比赛对象池 **/
|
|
|
- public Queue<Contest> contestPool;
|
|
|
- /** 最大空闲比赛数量 **/
|
|
|
- private int maxIdleContest;
|
|
|
- /** 清理线程 **/
|
|
|
- private ScheduledExecutorService cleaner;
|
|
|
-
|
|
|
+ /** 比赛对象池 **/
|
|
|
+ public ContestPool contestPool;
|
|
|
/** 比赛缓存 **/
|
|
|
public Map<Integer, Contest> contestMap = new ConcurrentHashMap<>();
|
|
|
|
|
@@ -40,66 +34,12 @@ public class ContestService {
|
|
|
*/
|
|
|
public void init(int maxIdleContest) {
|
|
|
logger.info("初始化官方比赛服务...");
|
|
|
- this.contestPool = new ConcurrentLinkedQueue<>();
|
|
|
- this.maxIdleContest = maxIdleContest;
|
|
|
- this.cleaner = Executors.newSingleThreadScheduledExecutor();
|
|
|
- // 定期清理空闲比赛
|
|
|
- this.cleaner.scheduleAtFixedRate(this::cleanIdleContest, 10, 30, TimeUnit.SECONDS);
|
|
|
-
|
|
|
+ // 初始化对象池
|
|
|
+ this.contestPool = new ContestPool(maxIdleContest);
|
|
|
//todo 测试创建一个比赛,5分钟后开始
|
|
|
this.creatContest(1, 1001);
|
|
|
}
|
|
|
|
|
|
- /**
|
|
|
- * 获取比赛对象
|
|
|
- *
|
|
|
- * @param roomType 房间类型
|
|
|
- * @return
|
|
|
- */
|
|
|
- public Contest acquireContest(int roomType) {
|
|
|
- Contest contest = this.contestPool.poll();
|
|
|
- if (contest == null) {
|
|
|
- // 创建指定类型的比赛
|
|
|
- contest = new Contest();
|
|
|
- }
|
|
|
- return contest;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 归还比赛对象
|
|
|
- */
|
|
|
- public void releaseContest(Contest contest) {
|
|
|
- if (contest != null) {
|
|
|
- this.contestPool.offer(contest); // 放回池中
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 定期清理空闲比赛对象
|
|
|
- */
|
|
|
- private void cleanIdleContest() {
|
|
|
- while (this.contestPool.size() > maxIdleContest) {
|
|
|
- Contest contest = this.contestPool.poll();
|
|
|
- if (contest != null) {
|
|
|
- // 销毁比赛,释放资源
|
|
|
- contest.destroy();
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 关闭对象池
|
|
|
- */
|
|
|
- public void shutdown() {
|
|
|
- this.cleaner.shutdownNow();
|
|
|
- this.contestPool.forEach(Contest::destroy);
|
|
|
- this.contestPool.clear();
|
|
|
- }
|
|
|
-
|
|
|
- public int getAvailableContest() {
|
|
|
- return this.contestPool.size();
|
|
|
- }
|
|
|
-
|
|
|
/**
|
|
|
* 获取玩家报名的比赛
|
|
|
*
|
|
@@ -124,7 +64,7 @@ public class ContestService {
|
|
|
*/
|
|
|
public Contest creatContest(int roomType, int contestId) {
|
|
|
// 从对象池获取比赛实例
|
|
|
- Contest contest = this.acquireContest(roomType);
|
|
|
+ Contest contest = this.contestPool.acquireContest(roomType);
|
|
|
// 初始化比赛数据
|
|
|
contest.init(roomType, contestId);
|
|
|
// 开始主线程逻辑
|