2
0

ThreadPoolManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 com.l2jserver.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 org.mmocore.network.ReceivablePacket;
  26. import com.l2jserver.Config;
  27. import com.l2jserver.gameserver.network.L2GameClient;
  28. import com.l2jserver.gameserver.util.StringUtil;
  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 com.l2jserver.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. public ScheduledThreadPoolExecutor _effectsScheduledThreadPool;
  64. private ScheduledThreadPoolExecutor _generalScheduledThreadPool;
  65. private ThreadPoolExecutor _generalPacketsThreadPool;
  66. private ThreadPoolExecutor _ioPacketsThreadPool;
  67. // will be really used in the next AI implementation.
  68. private ThreadPoolExecutor _aiThreadPool;
  69. private ThreadPoolExecutor _generalThreadPool;
  70. // temp
  71. private ScheduledThreadPoolExecutor _aiScheduledThreadPool;
  72. /** temp workaround for VM issue */
  73. private static final long MAX_DELAY = Long.MAX_VALUE / 1000000 / 2;
  74. private boolean _shutdown;
  75. public static ThreadPoolManager getInstance()
  76. {
  77. return SingletonHolder._instance;
  78. }
  79. private ThreadPoolManager()
  80. {
  81. _effectsScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_EFFECTS, new PriorityThreadFactory("EffectsSTPool", Thread.NORM_PRIORITY));
  82. _generalScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_GENERAL, new PriorityThreadFactory("GeneralSTPool", Thread.NORM_PRIORITY));
  83. _ioPacketsThreadPool = new ThreadPoolExecutor(Config.IO_PACKET_THREAD_CORE_SIZE, Integer.MAX_VALUE, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new PriorityThreadFactory("I/O Packet Pool", Thread.NORM_PRIORITY + 1));
  84. _generalPacketsThreadPool = new ThreadPoolExecutor(Config.GENERAL_PACKET_THREAD_CORE_SIZE, Config.GENERAL_PACKET_THREAD_CORE_SIZE + 2, 15L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new PriorityThreadFactory("Normal Packet Pool", Thread.NORM_PRIORITY + 1));
  85. _generalThreadPool = new ThreadPoolExecutor(Config.GENERAL_THREAD_CORE_SIZE, Config.GENERAL_THREAD_CORE_SIZE + 2, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new PriorityThreadFactory("General Pool", Thread.NORM_PRIORITY));
  86. // will be really used in the next AI implementation.
  87. _aiThreadPool = new ThreadPoolExecutor(1, Config.AI_MAX_THREAD, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
  88. _aiScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.AI_MAX_THREAD, new PriorityThreadFactory("AISTPool", Thread.NORM_PRIORITY));
  89. }
  90. public static long validateDelay(long delay)
  91. {
  92. if (delay < 0)
  93. delay = 0;
  94. else if (delay > MAX_DELAY)
  95. delay = MAX_DELAY;
  96. return delay;
  97. }
  98. public ScheduledFuture<?> scheduleEffect(Runnable r, long delay)
  99. {
  100. try
  101. {
  102. delay = ThreadPoolManager.validateDelay(delay);
  103. return _effectsScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  104. }
  105. catch (RejectedExecutionException e)
  106. {
  107. return null;
  108. }
  109. }
  110. public ScheduledFuture<?> scheduleEffectAtFixedRate(Runnable r, long initial, long delay)
  111. {
  112. try
  113. {
  114. delay = ThreadPoolManager.validateDelay(delay);
  115. initial = ThreadPoolManager.validateDelay(initial);
  116. return _effectsScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  117. }
  118. catch (RejectedExecutionException e)
  119. {
  120. return null; /* shutdown, ignore */
  121. }
  122. }
  123. public boolean removeEffect(Runnable r)
  124. {
  125. return _effectsScheduledThreadPool.remove(r);
  126. }
  127. public ScheduledFuture<?> scheduleGeneral(Runnable r, long delay)
  128. {
  129. try
  130. {
  131. delay = ThreadPoolManager.validateDelay(delay);
  132. return _generalScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  133. }
  134. catch (RejectedExecutionException e)
  135. {
  136. return null; /* shutdown, ignore */
  137. }
  138. }
  139. public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable r, long initial, long delay)
  140. {
  141. try
  142. {
  143. delay = ThreadPoolManager.validateDelay(delay);
  144. initial = ThreadPoolManager.validateDelay(initial);
  145. return _generalScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  146. }
  147. catch (RejectedExecutionException e)
  148. {
  149. return null; /* shutdown, ignore */
  150. }
  151. }
  152. public boolean removeGeneral(Runnable r)
  153. {
  154. return _generalScheduledThreadPool.remove(r);
  155. }
  156. public ScheduledFuture<?> scheduleAi(Runnable r, long delay)
  157. {
  158. try
  159. {
  160. delay = ThreadPoolManager.validateDelay(delay);
  161. return _aiScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  162. }
  163. catch (RejectedExecutionException e)
  164. {
  165. return null; /* shutdown, ignore */
  166. }
  167. }
  168. public ScheduledFuture<?> scheduleAiAtFixedRate(Runnable r, long initial, long delay)
  169. {
  170. try
  171. {
  172. delay = ThreadPoolManager.validateDelay(delay);
  173. initial = ThreadPoolManager.validateDelay(initial);
  174. return _aiScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  175. }
  176. catch (RejectedExecutionException e)
  177. {
  178. return null; /* shutdown, ignore */
  179. }
  180. }
  181. public void executePacket(ReceivablePacket<L2GameClient> pkt)
  182. {
  183. _generalPacketsThreadPool.execute(pkt);
  184. }
  185. public void executeCommunityPacket(Runnable r)
  186. {
  187. _generalPacketsThreadPool.execute(r);
  188. }
  189. public void executeIOPacket(ReceivablePacket<L2GameClient> pkt)
  190. {
  191. _ioPacketsThreadPool.execute(pkt);
  192. }
  193. public void executeTask(Runnable r)
  194. {
  195. _generalThreadPool.execute(r);
  196. }
  197. public void executeAi(Runnable r)
  198. {
  199. _aiThreadPool.execute(r);
  200. }
  201. public String[] getStats()
  202. {
  203. return new String[] {
  204. "STP:",
  205. " + Effects:",
  206. " |- ActiveThreads: " + _effectsScheduledThreadPool.getActiveCount(),
  207. " |- getCorePoolSize: " + _effectsScheduledThreadPool.getCorePoolSize(),
  208. " |- PoolSize: " + _effectsScheduledThreadPool.getPoolSize(),
  209. " |- MaximumPoolSize: " + _effectsScheduledThreadPool.getMaximumPoolSize(),
  210. " |- CompletedTasks: " + _effectsScheduledThreadPool.getCompletedTaskCount(),
  211. " |- ScheduledTasks: " + (_effectsScheduledThreadPool.getTaskCount() - _effectsScheduledThreadPool.getCompletedTaskCount()),
  212. " | -------",
  213. " + General:",
  214. " |- ActiveThreads: " + _generalScheduledThreadPool.getActiveCount(),
  215. " |- getCorePoolSize: " + _generalScheduledThreadPool.getCorePoolSize(),
  216. " |- PoolSize: " + _generalScheduledThreadPool.getPoolSize(),
  217. " |- MaximumPoolSize: " + _generalScheduledThreadPool.getMaximumPoolSize(),
  218. " |- CompletedTasks: " + _generalScheduledThreadPool.getCompletedTaskCount(),
  219. " |- ScheduledTasks: " + (_generalScheduledThreadPool.getTaskCount() - _generalScheduledThreadPool.getCompletedTaskCount()),
  220. " | -------",
  221. " + AI:",
  222. " |- ActiveThreads: " + _aiScheduledThreadPool.getActiveCount(),
  223. " |- getCorePoolSize: " + _aiScheduledThreadPool.getCorePoolSize(),
  224. " |- PoolSize: " + _aiScheduledThreadPool.getPoolSize(),
  225. " |- MaximumPoolSize: " + _aiScheduledThreadPool.getMaximumPoolSize(),
  226. " |- CompletedTasks: " + _aiScheduledThreadPool.getCompletedTaskCount(),
  227. " |- ScheduledTasks: " + (_aiScheduledThreadPool.getTaskCount() - _aiScheduledThreadPool.getCompletedTaskCount()),
  228. "TP:",
  229. " + Packets:",
  230. " |- ActiveThreads: " + _generalPacketsThreadPool.getActiveCount(),
  231. " |- getCorePoolSize: " + _generalPacketsThreadPool.getCorePoolSize(),
  232. " |- MaximumPoolSize: " + _generalPacketsThreadPool.getMaximumPoolSize(),
  233. " |- LargestPoolSize: " + _generalPacketsThreadPool.getLargestPoolSize(),
  234. " |- PoolSize: " + _generalPacketsThreadPool.getPoolSize(),
  235. " |- CompletedTasks: " + _generalPacketsThreadPool.getCompletedTaskCount(),
  236. " |- QueuedTasks: " + _generalPacketsThreadPool.getQueue().size(),
  237. " | -------",
  238. " + I/O Packets:",
  239. " |- ActiveThreads: " + _ioPacketsThreadPool.getActiveCount(),
  240. " |- getCorePoolSize: " + _ioPacketsThreadPool.getCorePoolSize(),
  241. " |- MaximumPoolSize: " + _ioPacketsThreadPool.getMaximumPoolSize(),
  242. " |- LargestPoolSize: " + _ioPacketsThreadPool.getLargestPoolSize(),
  243. " |- PoolSize: " + _ioPacketsThreadPool.getPoolSize(),
  244. " |- CompletedTasks: " + _ioPacketsThreadPool.getCompletedTaskCount(),
  245. " |- QueuedTasks: " + _ioPacketsThreadPool.getQueue().size(),
  246. " | -------",
  247. " + General Tasks:",
  248. " |- ActiveThreads: " + _generalThreadPool.getActiveCount(),
  249. " |- getCorePoolSize: " + _generalThreadPool.getCorePoolSize(),
  250. " |- MaximumPoolSize: " + _generalThreadPool.getMaximumPoolSize(),
  251. " |- LargestPoolSize: " + _generalThreadPool.getLargestPoolSize(),
  252. " |- PoolSize: " + _generalThreadPool.getPoolSize(),
  253. " |- CompletedTasks: " + _generalThreadPool.getCompletedTaskCount(),
  254. " |- QueuedTasks: " + _generalThreadPool.getQueue().size(),
  255. " | -------",
  256. " + AI:",
  257. " |- Not Done"
  258. };
  259. }
  260. private class PriorityThreadFactory implements ThreadFactory
  261. {
  262. private int _prio;
  263. private String _name;
  264. private AtomicInteger _threadNumber = new AtomicInteger(1);
  265. private ThreadGroup _group;
  266. public PriorityThreadFactory(String name, int prio)
  267. {
  268. _prio = prio;
  269. _name = name;
  270. _group = new ThreadGroup(_name);
  271. }
  272. /* (non-Javadoc)
  273. * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
  274. */
  275. public Thread newThread(Runnable r)
  276. {
  277. Thread t = new Thread(_group, r);
  278. t.setName(_name + "-" + _threadNumber.getAndIncrement());
  279. t.setPriority(_prio);
  280. return t;
  281. }
  282. public ThreadGroup getGroup()
  283. {
  284. return _group;
  285. }
  286. }
  287. /**
  288. *
  289. */
  290. public void shutdown()
  291. {
  292. _shutdown = true;
  293. try
  294. {
  295. _effectsScheduledThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  296. _generalScheduledThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  297. _generalPacketsThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  298. _ioPacketsThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  299. _generalThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  300. _aiThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  301. _effectsScheduledThreadPool.shutdown();
  302. _generalScheduledThreadPool.shutdown();
  303. _generalPacketsThreadPool.shutdown();
  304. _ioPacketsThreadPool.shutdown();
  305. _generalThreadPool.shutdown();
  306. _aiThreadPool.shutdown();
  307. _log.info("All ThreadPools are now stopped");
  308. }
  309. catch (InterruptedException e)
  310. {
  311. // TODO Auto-generated catch block
  312. e.printStackTrace();
  313. }
  314. }
  315. public boolean isShutdown()
  316. {
  317. return _shutdown;
  318. }
  319. /**
  320. *
  321. */
  322. public void purge()
  323. {
  324. _effectsScheduledThreadPool.purge();
  325. _generalScheduledThreadPool.purge();
  326. _aiScheduledThreadPool.purge();
  327. _ioPacketsThreadPool.purge();
  328. _generalPacketsThreadPool.purge();
  329. _generalThreadPool.purge();
  330. _aiThreadPool.purge();
  331. }
  332. /**
  333. *
  334. */
  335. public String getPacketStats()
  336. {
  337. final StringBuilder sb = new StringBuilder(1000);
  338. ThreadFactory tf = _generalPacketsThreadPool.getThreadFactory();
  339. if (tf instanceof PriorityThreadFactory)
  340. {
  341. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  342. int count = ptf.getGroup().activeCount();
  343. Thread[] threads = new Thread[count + 2];
  344. ptf.getGroup().enumerate(threads);
  345. StringUtil.append(sb, "General Packet Thread Pool:\r\n" + "Tasks in the queue: ", String.valueOf(_generalPacketsThreadPool.getQueue().size()), "\r\n"
  346. + "Showing threads stack trace:\r\n" + "There should be ", String.valueOf(count), " Threads\r\n");
  347. for (Thread t : threads)
  348. {
  349. if (t == null)
  350. continue;
  351. StringUtil.append(sb, t.getName(), "\r\n");
  352. for (StackTraceElement ste : t.getStackTrace())
  353. {
  354. StringUtil.append(sb, ste.toString(), "\r\n");
  355. }
  356. }
  357. }
  358. sb.append("Packet Tp stack traces printed.\r\n");
  359. return sb.toString();
  360. }
  361. public String getIOPacketStats()
  362. {
  363. final StringBuilder sb = new StringBuilder(1000);
  364. ThreadFactory tf = _ioPacketsThreadPool.getThreadFactory();
  365. if (tf instanceof PriorityThreadFactory)
  366. {
  367. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  368. int count = ptf.getGroup().activeCount();
  369. Thread[] threads = new Thread[count + 2];
  370. ptf.getGroup().enumerate(threads);
  371. StringUtil.append(sb, "I/O Packet Thread Pool:\r\n" + "Tasks in the queue: ", String.valueOf(_ioPacketsThreadPool.getQueue().size()), "\r\n"
  372. + "Showing threads stack trace:\r\n" + "There should be ", String.valueOf(count), " Threads\r\n");
  373. for (Thread t : threads)
  374. {
  375. if (t == null)
  376. continue;
  377. StringUtil.append(sb, t.getName(), "\r\n");
  378. for (StackTraceElement ste : t.getStackTrace())
  379. {
  380. StringUtil.append(sb, ste.toString(), "\r\n");
  381. }
  382. }
  383. }
  384. sb.append("Packet Tp stack traces printed.\r\n");
  385. return sb.toString();
  386. }
  387. public String getGeneralStats()
  388. {
  389. final StringBuilder sb = new StringBuilder(1000);
  390. ThreadFactory tf = _generalThreadPool.getThreadFactory();
  391. if (tf instanceof PriorityThreadFactory)
  392. {
  393. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  394. int count = ptf.getGroup().activeCount();
  395. Thread[] threads = new Thread[count + 2];
  396. ptf.getGroup().enumerate(threads);
  397. StringUtil.append(sb, "General Thread Pool:\r\n" + "Tasks in the queue: ", String.valueOf(_generalThreadPool.getQueue().size()), "\r\n"
  398. + "Showing threads stack trace:\r\n" + "There should be ", String.valueOf(count), " Threads\r\n");
  399. for (Thread t : threads)
  400. {
  401. if (t == null)
  402. continue;
  403. StringUtil.append(sb, t.getName(), "\r\n");
  404. for (StackTraceElement ste : t.getStackTrace())
  405. {
  406. StringUtil.append(sb, ste.toString(), "\r\n");
  407. }
  408. }
  409. }
  410. sb.append("Packet Tp stack traces printed.\r\n");
  411. return sb.toString();
  412. }
  413. @SuppressWarnings("synthetic-access")
  414. private static class SingletonHolder
  415. {
  416. protected static final ThreadPoolManager _instance = new ThreadPoolManager();
  417. }
  418. }