ThreadPoolManager.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package net.sf.l2j.gameserver;
  16. import java.util.concurrent.LinkedBlockingQueue;
  17. import java.util.concurrent.RejectedExecutionException;
  18. import java.util.concurrent.ScheduledFuture;
  19. import java.util.concurrent.ScheduledThreadPoolExecutor;
  20. import java.util.concurrent.ThreadFactory;
  21. import java.util.concurrent.ThreadPoolExecutor;
  22. import java.util.concurrent.TimeUnit;
  23. import java.util.concurrent.atomic.AtomicInteger;
  24. import java.util.logging.Logger;
  25. import net.sf.l2j.Config;
  26. import net.sf.l2j.gameserver.network.L2GameClient;
  27. import net.sf.l2j.gameserver.util.StringUtil;
  28. import org.mmocore.network.ReceivablePacket;
  29. /**
  30. * <p>This class is made to handle all the ThreadPools used in L2j.</p>
  31. * <p>Scheduled Tasks can either be sent to a {@link #_generalScheduledThreadPool "general"} or {@link #_effectsScheduledThreadPool "effects"} {@link ScheduledThreadPoolExecutor ScheduledThreadPool}:
  32. * The "effects" one is used for every effects (skills, hp/mp regen ...) while the "general" one is used for
  33. * everything else that needs to be scheduled.<br>
  34. * There also is an {@link #_aiScheduledThreadPool "ai"} {@link ScheduledThreadPoolExecutor ScheduledThreadPool} used for AI Tasks.</p>
  35. * <p>Tasks can be sent to {@link ScheduledThreadPoolExecutor ScheduledThreadPool} either with:
  36. * <ul>
  37. * <li>{@link #scheduleEffect(Runnable, long)} : for effects Tasks that needs to be executed only once.</li>
  38. * <li>{@link #scheduleGeneral(Runnable, long)} : for scheduled Tasks that needs to be executed once.</li>
  39. * <li>{@link #scheduleAi(Runnable, long)} : for AI Tasks that needs to be executed once</li>
  40. * </ul>
  41. * or
  42. * <ul>
  43. * <li>{@link #scheduleEffectAtFixedRate(Runnable, long, long)(Runnable, long)} : for effects Tasks that needs to be executed periodicaly.</li>
  44. * <li>{@link #scheduleGeneralAtFixedRate(Runnable, long, long)(Runnable, long)} : for scheduled Tasks that needs to be executed periodicaly.</li>
  45. * <li>{@link #scheduleAiAtFixedRate(Runnable, long, long)(Runnable, long)} : for AI Tasks that needs to be executed periodicaly</li>
  46. * </ul></p>
  47. *
  48. * <p>For all Tasks that should be executed with no delay asynchronously in a ThreadPool there also are usual {@link ThreadPoolExecutor ThreadPools}
  49. * that can grow/shrink according to their load.:
  50. * <ul>
  51. * <li>{@link #_generalPacketsThreadPool GeneralPackets} where most packets handler are executed.</li>
  52. * <li>{@link #_ioPacketsThreadPool I/O Packets} where all the i/o packets are executed.</li>
  53. * <li>There will be an AI ThreadPool where AI events should be executed</li>
  54. * <li>A general ThreadPool where everything else that needs to run asynchronously with no delay should be executed ({@link net.sf.l2j.gameserver.model.actor.knownlist KnownList} updates, SQL updates/inserts...)?</li>
  55. * </ul>
  56. * </p>
  57. * @author -Wooden-
  58. *
  59. */
  60. public class ThreadPoolManager
  61. {
  62. protected static final Logger _log = Logger.getLogger(ThreadPoolManager.class.getName());
  63. private static ThreadPoolManager _instance;
  64. public ScheduledThreadPoolExecutor _effectsScheduledThreadPool;
  65. private ScheduledThreadPoolExecutor _generalScheduledThreadPool;
  66. private ThreadPoolExecutor _generalPacketsThreadPool;
  67. private ThreadPoolExecutor _ioPacketsThreadPool;
  68. // will be really used in the next AI implementation.
  69. private ThreadPoolExecutor _aiThreadPool;
  70. private ThreadPoolExecutor _generalThreadPool;
  71. // temp
  72. private ScheduledThreadPoolExecutor _aiScheduledThreadPool;
  73. /** temp workaround for VM issue */
  74. private static final long MAX_DELAY = Long.MAX_VALUE/1000000/2;
  75. private boolean _shutdown;
  76. public static ThreadPoolManager getInstance()
  77. {
  78. if(_instance == null)
  79. {
  80. _instance = new ThreadPoolManager();
  81. }
  82. return _instance;
  83. }
  84. private ThreadPoolManager()
  85. {
  86. _effectsScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_EFFECTS, new PriorityThreadFactory("EffectsSTPool", Thread.NORM_PRIORITY));
  87. _generalScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_GENERAL, new PriorityThreadFactory("GeneralSTPool", Thread.NORM_PRIORITY));
  88. _ioPacketsThreadPool = new ThreadPoolExecutor(Config.IO_PACKET_THREAD_CORE_SIZE, Integer.MAX_VALUE,
  89. 5L, TimeUnit.SECONDS,
  90. new LinkedBlockingQueue<Runnable>(),
  91. new PriorityThreadFactory("I/O Packet Pool",Thread.NORM_PRIORITY+1));
  92. _generalPacketsThreadPool = new ThreadPoolExecutor(Config.GENERAL_PACKET_THREAD_CORE_SIZE, Config.GENERAL_PACKET_THREAD_CORE_SIZE+2,
  93. 15L, TimeUnit.SECONDS,
  94. new LinkedBlockingQueue<Runnable>(),
  95. new PriorityThreadFactory("Normal Packet Pool",Thread.NORM_PRIORITY+1));
  96. _generalThreadPool = new ThreadPoolExecutor(Config.GENERAL_THREAD_CORE_SIZE, Config.GENERAL_THREAD_CORE_SIZE+2,
  97. 5L, TimeUnit.SECONDS,
  98. new LinkedBlockingQueue<Runnable>(),
  99. new PriorityThreadFactory("General Pool",Thread.NORM_PRIORITY));
  100. // will be really used in the next AI implementation.
  101. _aiThreadPool = new ThreadPoolExecutor(1, Config.AI_MAX_THREAD,
  102. 10L, TimeUnit.SECONDS,
  103. new LinkedBlockingQueue<Runnable>());
  104. _aiScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.AI_MAX_THREAD, new PriorityThreadFactory("AISTPool", Thread.NORM_PRIORITY));
  105. }
  106. public static long validateDelay(long delay)
  107. {
  108. if (delay < 0)
  109. {
  110. delay = 0;
  111. }
  112. else if (delay > MAX_DELAY)
  113. {
  114. delay = MAX_DELAY;
  115. }
  116. return delay;
  117. }
  118. public ScheduledFuture<?> scheduleEffect(Runnable r, long delay)
  119. {
  120. try
  121. {
  122. delay = ThreadPoolManager.validateDelay(delay);
  123. return _effectsScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  124. }
  125. catch (RejectedExecutionException e)
  126. {
  127. return null;
  128. }
  129. }
  130. public ScheduledFuture<?> scheduleEffectAtFixedRate(Runnable r, long initial, long delay)
  131. {
  132. try
  133. {
  134. delay = ThreadPoolManager.validateDelay(delay);
  135. initial = ThreadPoolManager.validateDelay(initial);
  136. return _effectsScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  137. }
  138. catch (RejectedExecutionException e)
  139. {
  140. return null; /* shutdown, ignore */
  141. }
  142. }
  143. public ScheduledFuture<?> scheduleGeneral(Runnable r, long delay)
  144. {
  145. try
  146. {
  147. delay = ThreadPoolManager.validateDelay(delay);
  148. return _generalScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  149. }
  150. catch (RejectedExecutionException e)
  151. {
  152. return null; /* shutdown, ignore */
  153. }
  154. }
  155. public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable r, long initial, long delay)
  156. {
  157. try
  158. {
  159. delay = ThreadPoolManager.validateDelay(delay);
  160. initial = ThreadPoolManager.validateDelay(initial);
  161. return _generalScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  162. }
  163. catch (RejectedExecutionException e)
  164. {
  165. return null; /* shutdown, ignore */
  166. }
  167. }
  168. public ScheduledFuture<?> scheduleAi(Runnable r, long delay)
  169. {
  170. try
  171. {
  172. delay = ThreadPoolManager.validateDelay(delay);
  173. return _aiScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  174. }
  175. catch (RejectedExecutionException e)
  176. {
  177. return null; /* shutdown, ignore */
  178. }
  179. }
  180. public ScheduledFuture<?> scheduleAiAtFixedRate(Runnable r, long initial, long delay)
  181. {
  182. try
  183. {
  184. delay = ThreadPoolManager.validateDelay(delay);
  185. initial = ThreadPoolManager.validateDelay(initial);
  186. return _aiScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  187. }
  188. catch (RejectedExecutionException e)
  189. {
  190. return null; /* shutdown, ignore */
  191. }
  192. }
  193. public void executePacket(ReceivablePacket<L2GameClient> pkt)
  194. {
  195. _generalPacketsThreadPool.execute(pkt);
  196. }
  197. public void executeIOPacket(ReceivablePacket<L2GameClient> pkt)
  198. {
  199. _ioPacketsThreadPool.execute(pkt);
  200. }
  201. public void executeTask(Runnable r)
  202. {
  203. _generalThreadPool.execute(r);
  204. }
  205. public void executeAi(Runnable r)
  206. {
  207. _aiThreadPool.execute(r);
  208. }
  209. public String[] getStats()
  210. {
  211. return new String[] {
  212. "STP:",
  213. " + Effects:",
  214. " |- ActiveThreads: "+_effectsScheduledThreadPool.getActiveCount(),
  215. " |- getCorePoolSize: "+_effectsScheduledThreadPool.getCorePoolSize(),
  216. " |- PoolSize: "+_effectsScheduledThreadPool.getPoolSize(),
  217. " |- MaximumPoolSize: "+_effectsScheduledThreadPool.getMaximumPoolSize(),
  218. " |- CompletedTasks: "+_effectsScheduledThreadPool.getCompletedTaskCount(),
  219. " |- ScheduledTasks: "+(_effectsScheduledThreadPool.getTaskCount() - _effectsScheduledThreadPool.getCompletedTaskCount()),
  220. " | -------",
  221. " + General:",
  222. " |- ActiveThreads: "+_generalScheduledThreadPool.getActiveCount(),
  223. " |- getCorePoolSize: "+_generalScheduledThreadPool.getCorePoolSize(),
  224. " |- PoolSize: "+_generalScheduledThreadPool.getPoolSize(),
  225. " |- MaximumPoolSize: "+_generalScheduledThreadPool.getMaximumPoolSize(),
  226. " |- CompletedTasks: "+_generalScheduledThreadPool.getCompletedTaskCount(),
  227. " |- ScheduledTasks: "+(_generalScheduledThreadPool.getTaskCount() - _generalScheduledThreadPool.getCompletedTaskCount()),
  228. " | -------",
  229. " + AI:",
  230. " |- ActiveThreads: "+_aiScheduledThreadPool.getActiveCount(),
  231. " |- getCorePoolSize: "+_aiScheduledThreadPool.getCorePoolSize(),
  232. " |- PoolSize: "+_aiScheduledThreadPool.getPoolSize(),
  233. " |- MaximumPoolSize: "+_aiScheduledThreadPool.getMaximumPoolSize(),
  234. " |- CompletedTasks: "+_aiScheduledThreadPool.getCompletedTaskCount(),
  235. " |- ScheduledTasks: "+(_aiScheduledThreadPool.getTaskCount() - _aiScheduledThreadPool.getCompletedTaskCount()),
  236. "TP:",
  237. " + Packets:",
  238. " |- ActiveThreads: "+_generalPacketsThreadPool.getActiveCount(),
  239. " |- getCorePoolSize: "+_generalPacketsThreadPool.getCorePoolSize(),
  240. " |- MaximumPoolSize: "+_generalPacketsThreadPool.getMaximumPoolSize(),
  241. " |- LargestPoolSize: "+_generalPacketsThreadPool.getLargestPoolSize(),
  242. " |- PoolSize: "+_generalPacketsThreadPool.getPoolSize(),
  243. " |- CompletedTasks: "+_generalPacketsThreadPool.getCompletedTaskCount(),
  244. " |- QueuedTasks: "+_generalPacketsThreadPool.getQueue().size(),
  245. " | -------",
  246. " + I/O Packets:",
  247. " |- ActiveThreads: "+_ioPacketsThreadPool.getActiveCount(),
  248. " |- getCorePoolSize: "+_ioPacketsThreadPool.getCorePoolSize(),
  249. " |- MaximumPoolSize: "+_ioPacketsThreadPool.getMaximumPoolSize(),
  250. " |- LargestPoolSize: "+_ioPacketsThreadPool.getLargestPoolSize(),
  251. " |- PoolSize: "+_ioPacketsThreadPool.getPoolSize(),
  252. " |- CompletedTasks: "+_ioPacketsThreadPool.getCompletedTaskCount(),
  253. " |- QueuedTasks: "+_ioPacketsThreadPool.getQueue().size(),
  254. " | -------",
  255. " + General Tasks:",
  256. " |- ActiveThreads: "+_generalThreadPool.getActiveCount(),
  257. " |- getCorePoolSize: "+_generalThreadPool.getCorePoolSize(),
  258. " |- MaximumPoolSize: "+_generalThreadPool.getMaximumPoolSize(),
  259. " |- LargestPoolSize: "+_generalThreadPool.getLargestPoolSize(),
  260. " |- PoolSize: "+_generalThreadPool.getPoolSize(),
  261. " |- CompletedTasks: "+_generalThreadPool.getCompletedTaskCount(),
  262. " |- QueuedTasks: "+_generalThreadPool.getQueue().size(),
  263. " | -------",
  264. " + AI:",
  265. " |- Not Done"
  266. };
  267. }
  268. private class PriorityThreadFactory implements ThreadFactory
  269. {
  270. private int _prio;
  271. private String _name;
  272. private AtomicInteger _threadNumber = new AtomicInteger(1);
  273. private ThreadGroup _group;
  274. public PriorityThreadFactory(String name, int prio)
  275. {
  276. _prio = prio;
  277. _name = name;
  278. _group = new ThreadGroup(_name);
  279. }
  280. /* (non-Javadoc)
  281. * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
  282. */
  283. public Thread newThread(Runnable r)
  284. {
  285. Thread t = new Thread(_group,r);
  286. t.setName(_name+"-"+_threadNumber.getAndIncrement());
  287. t.setPriority(_prio);
  288. return t;
  289. }
  290. public ThreadGroup getGroup()
  291. {
  292. return _group;
  293. }
  294. }
  295. /**
  296. *
  297. */
  298. public void shutdown()
  299. {
  300. _shutdown = true;
  301. try
  302. {
  303. _effectsScheduledThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  304. _generalScheduledThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  305. _generalPacketsThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  306. _ioPacketsThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  307. _generalThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  308. _aiThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  309. _effectsScheduledThreadPool.shutdown();
  310. _generalScheduledThreadPool.shutdown();
  311. _generalPacketsThreadPool.shutdown();
  312. _ioPacketsThreadPool.shutdown();
  313. _generalThreadPool.shutdown();
  314. _aiThreadPool.shutdown();
  315. _log.info("All ThreadPools are now stoped");
  316. }
  317. catch (InterruptedException e)
  318. {
  319. // TODO Auto-generated catch block
  320. e.printStackTrace();
  321. }
  322. }
  323. public boolean isShutdown()
  324. {
  325. return _shutdown;
  326. }
  327. /**
  328. *
  329. */
  330. public void purge()
  331. {
  332. _effectsScheduledThreadPool.purge();
  333. _generalScheduledThreadPool.purge();
  334. _aiScheduledThreadPool.purge();
  335. _ioPacketsThreadPool.purge();
  336. _generalPacketsThreadPool.purge();
  337. _generalThreadPool.purge();
  338. _aiThreadPool.purge();
  339. }
  340. /**
  341. *
  342. */
  343. public String getPacketStats() {
  344. final StringBuilder sb = new StringBuilder(1000);
  345. ThreadFactory tf = _generalPacketsThreadPool.getThreadFactory();
  346. if (tf instanceof PriorityThreadFactory) {
  347. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  348. int count = ptf.getGroup().activeCount();
  349. Thread[] threads = new Thread[count+2];
  350. ptf.getGroup().enumerate(threads);
  351. StringUtil.append(sb,
  352. "General Packet Thread Pool:\r\n" +
  353. "Tasks in the queue: ",
  354. String.valueOf(_generalPacketsThreadPool.getQueue().size()),
  355. "\r\n" +
  356. "Showing threads stack trace:\r\n" +
  357. "There should be ",
  358. String.valueOf(count),
  359. " Threads\r\n");
  360. for(Thread t : threads) {
  361. if(t == null)
  362. continue;
  363. StringUtil.append(sb,
  364. t.getName(),
  365. "\r\n");
  366. for(StackTraceElement ste :t.getStackTrace()) {
  367. StringUtil.append(sb,
  368. ste.toString(),
  369. "\r\n");
  370. }
  371. }
  372. }
  373. sb.append("Packet Tp stack traces printed.\r\n");
  374. return sb.toString();
  375. }
  376. public String getIOPacketStats() {
  377. final StringBuilder sb = new StringBuilder(1000);
  378. ThreadFactory tf = _ioPacketsThreadPool.getThreadFactory();
  379. if (tf instanceof PriorityThreadFactory) {
  380. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  381. int count = ptf.getGroup().activeCount();
  382. Thread[] threads = new Thread[count+2];
  383. ptf.getGroup().enumerate(threads);
  384. StringUtil.append(sb,
  385. "I/O Packet Thread Pool:\r\n" +
  386. "Tasks in the queue: ",
  387. String.valueOf(_ioPacketsThreadPool.getQueue().size()),
  388. "\r\n" +
  389. "Showing threads stack trace:\r\n" +
  390. "There should be ",
  391. String.valueOf(count),
  392. " Threads\r\n");
  393. for(Thread t : threads) {
  394. if(t == null)
  395. continue;
  396. StringUtil.append(sb,
  397. t.getName(),
  398. "\r\n");
  399. for(StackTraceElement ste :t.getStackTrace()) {
  400. StringUtil.append(sb,
  401. ste.toString(),
  402. "\r\n");
  403. }
  404. }
  405. }
  406. sb.append("Packet Tp stack traces printed.\r\n");
  407. return sb.toString();
  408. }
  409. public String getGeneralStats() {
  410. final StringBuilder sb = new StringBuilder(1000);
  411. ThreadFactory tf = _generalThreadPool.getThreadFactory();
  412. if (tf instanceof PriorityThreadFactory) {
  413. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  414. int count = ptf.getGroup().activeCount();
  415. Thread[] threads = new Thread[count+2];
  416. ptf.getGroup().enumerate(threads);
  417. StringUtil.append(sb,
  418. "General Thread Pool:\r\n" +
  419. "Tasks in the queue: ",
  420. String.valueOf(_generalThreadPool.getQueue().size()),
  421. "\r\n" +
  422. "Showing threads stack trace:\r\n" +
  423. "There should be ",
  424. String.valueOf(count),
  425. " Threads\r\n");
  426. for(Thread t : threads) {
  427. if(t == null)
  428. continue;
  429. StringUtil.append(sb,
  430. t.getName(),
  431. "\r\n");
  432. for(StackTraceElement ste :t.getStackTrace()) {
  433. StringUtil.append(sb,
  434. ste.toString(),
  435. "\r\n");
  436. }
  437. }
  438. }
  439. sb.append("Packet Tp stack traces printed.\r\n");
  440. return sb.toString();
  441. }
  442. }