ThreadPoolManager.java 18 KB

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