ThreadPoolManager.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. private ScheduledThreadPoolExecutor _effectsScheduledThreadPool;
  91. private ScheduledThreadPoolExecutor _generalScheduledThreadPool;
  92. private 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. private 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. scheduleGeneralAtFixedRate(new PurgeTask(), 10*60*1000l, 5*60*1000l);
  112. }
  113. public static long validateDelay(long delay)
  114. {
  115. if (delay < 0)
  116. delay = 0;
  117. else if (delay > MAX_DELAY)
  118. delay = MAX_DELAY;
  119. return delay;
  120. }
  121. public ScheduledFuture<?> scheduleEffect(Runnable r, long delay)
  122. {
  123. try
  124. {
  125. delay = ThreadPoolManager.validateDelay(delay);
  126. return _effectsScheduledThreadPool.schedule(new RunnableWrapper(r), delay, TimeUnit.MILLISECONDS);
  127. }
  128. catch (RejectedExecutionException e)
  129. {
  130. return null;
  131. }
  132. }
  133. public ScheduledFuture<?> scheduleEffectAtFixedRate(Runnable r, long initial, long delay)
  134. {
  135. try
  136. {
  137. delay = ThreadPoolManager.validateDelay(delay);
  138. initial = ThreadPoolManager.validateDelay(initial);
  139. return _effectsScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(r), initial, delay, TimeUnit.MILLISECONDS);
  140. }
  141. catch (RejectedExecutionException e)
  142. {
  143. return null; /* shutdown, ignore */
  144. }
  145. }
  146. @Deprecated
  147. public boolean removeEffect(RunnableScheduledFuture<?> r)
  148. {
  149. return _effectsScheduledThreadPool.remove(r);
  150. }
  151. public ScheduledFuture<?> scheduleGeneral(Runnable r, long delay)
  152. {
  153. try
  154. {
  155. delay = ThreadPoolManager.validateDelay(delay);
  156. return _generalScheduledThreadPool.schedule(new RunnableWrapper(r), delay, TimeUnit.MILLISECONDS);
  157. }
  158. catch (RejectedExecutionException e)
  159. {
  160. return null; /* shutdown, ignore */
  161. }
  162. }
  163. public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable r, long initial, long delay)
  164. {
  165. try
  166. {
  167. delay = ThreadPoolManager.validateDelay(delay);
  168. initial = ThreadPoolManager.validateDelay(initial);
  169. return _generalScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(r), initial, delay, TimeUnit.MILLISECONDS);
  170. }
  171. catch (RejectedExecutionException e)
  172. {
  173. return null; /* shutdown, ignore */
  174. }
  175. }
  176. @Deprecated
  177. public boolean removeGeneral(RunnableScheduledFuture<?> r)
  178. {
  179. return _generalScheduledThreadPool.remove(r);
  180. }
  181. public ScheduledFuture<?> scheduleAi(Runnable r, long delay)
  182. {
  183. try
  184. {
  185. delay = ThreadPoolManager.validateDelay(delay);
  186. return _aiScheduledThreadPool.schedule(new RunnableWrapper(r), delay, TimeUnit.MILLISECONDS);
  187. }
  188. catch (RejectedExecutionException e)
  189. {
  190. return null; /* shutdown, ignore */
  191. }
  192. }
  193. public ScheduledFuture<?> scheduleAiAtFixedRate(Runnable r, long initial, long delay)
  194. {
  195. try
  196. {
  197. delay = ThreadPoolManager.validateDelay(delay);
  198. initial = ThreadPoolManager.validateDelay(initial);
  199. return _aiScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(r), initial, delay, TimeUnit.MILLISECONDS);
  200. }
  201. catch (RejectedExecutionException e)
  202. {
  203. return null; /* shutdown, ignore */
  204. }
  205. }
  206. public void executePacket(Runnable pkt)
  207. {
  208. _generalPacketsThreadPool.execute(pkt);
  209. }
  210. public void executeCommunityPacket(Runnable r)
  211. {
  212. _generalPacketsThreadPool.execute(r);
  213. }
  214. public void executeIOPacket(Runnable pkt)
  215. {
  216. _ioPacketsThreadPool.execute(pkt);
  217. }
  218. public void executeTask(Runnable r)
  219. {
  220. _generalThreadPool.execute(r);
  221. }
  222. public void executeAi(Runnable r)
  223. {
  224. _aiScheduledThreadPool.execute(new RunnableWrapper(r));
  225. }
  226. public String[] getStats()
  227. {
  228. return new String[] {
  229. "STP:",
  230. " + Effects:",
  231. " |- ActiveThreads: " + _effectsScheduledThreadPool.getActiveCount(),
  232. " |- getCorePoolSize: " + _effectsScheduledThreadPool.getCorePoolSize(),
  233. " |- PoolSize: " + _effectsScheduledThreadPool.getPoolSize(),
  234. " |- MaximumPoolSize: " + _effectsScheduledThreadPool.getMaximumPoolSize(),
  235. " |- CompletedTasks: " + _effectsScheduledThreadPool.getCompletedTaskCount(),
  236. " |- ScheduledTasks: " + (_effectsScheduledThreadPool.getTaskCount() - _effectsScheduledThreadPool.getCompletedTaskCount()),
  237. " | -------",
  238. " + General:",
  239. " |- ActiveThreads: " + _generalScheduledThreadPool.getActiveCount(),
  240. " |- getCorePoolSize: " + _generalScheduledThreadPool.getCorePoolSize(),
  241. " |- PoolSize: " + _generalScheduledThreadPool.getPoolSize(),
  242. " |- MaximumPoolSize: " + _generalScheduledThreadPool.getMaximumPoolSize(),
  243. " |- CompletedTasks: " + _generalScheduledThreadPool.getCompletedTaskCount(),
  244. " |- ScheduledTasks: " + (_generalScheduledThreadPool.getTaskCount() - _generalScheduledThreadPool.getCompletedTaskCount()),
  245. " | -------",
  246. " + AI:",
  247. " |- ActiveThreads: " + _aiScheduledThreadPool.getActiveCount(),
  248. " |- getCorePoolSize: " + _aiScheduledThreadPool.getCorePoolSize(),
  249. " |- PoolSize: " + _aiScheduledThreadPool.getPoolSize(),
  250. " |- MaximumPoolSize: " + _aiScheduledThreadPool.getMaximumPoolSize(),
  251. " |- CompletedTasks: " + _aiScheduledThreadPool.getCompletedTaskCount(),
  252. " |- ScheduledTasks: " + (_aiScheduledThreadPool.getTaskCount() - _aiScheduledThreadPool.getCompletedTaskCount()),
  253. "TP:",
  254. " + Packets:",
  255. " |- ActiveThreads: " + _generalPacketsThreadPool.getActiveCount(),
  256. " |- getCorePoolSize: " + _generalPacketsThreadPool.getCorePoolSize(),
  257. " |- MaximumPoolSize: " + _generalPacketsThreadPool.getMaximumPoolSize(),
  258. " |- LargestPoolSize: " + _generalPacketsThreadPool.getLargestPoolSize(),
  259. " |- PoolSize: " + _generalPacketsThreadPool.getPoolSize(),
  260. " |- CompletedTasks: " + _generalPacketsThreadPool.getCompletedTaskCount(),
  261. " |- QueuedTasks: " + _generalPacketsThreadPool.getQueue().size(),
  262. " | -------",
  263. " + I/O Packets:",
  264. " |- ActiveThreads: " + _ioPacketsThreadPool.getActiveCount(),
  265. " |- getCorePoolSize: " + _ioPacketsThreadPool.getCorePoolSize(),
  266. " |- MaximumPoolSize: " + _ioPacketsThreadPool.getMaximumPoolSize(),
  267. " |- LargestPoolSize: " + _ioPacketsThreadPool.getLargestPoolSize(),
  268. " |- PoolSize: " + _ioPacketsThreadPool.getPoolSize(),
  269. " |- CompletedTasks: " + _ioPacketsThreadPool.getCompletedTaskCount(),
  270. " |- QueuedTasks: " + _ioPacketsThreadPool.getQueue().size(),
  271. " | -------",
  272. " + General Tasks:",
  273. " |- ActiveThreads: " + _generalThreadPool.getActiveCount(),
  274. " |- getCorePoolSize: " + _generalThreadPool.getCorePoolSize(),
  275. " |- MaximumPoolSize: " + _generalThreadPool.getMaximumPoolSize(),
  276. " |- LargestPoolSize: " + _generalThreadPool.getLargestPoolSize(),
  277. " |- PoolSize: " + _generalThreadPool.getPoolSize(),
  278. " |- CompletedTasks: " + _generalThreadPool.getCompletedTaskCount(),
  279. " |- QueuedTasks: " + _generalThreadPool.getQueue().size(),
  280. " | -------",
  281. " + Javolution stats:",
  282. " |- FastList: " + FastList.report(),
  283. " |- FastMap: " + FastMap.report(),
  284. " |- FastSet: " + FastSet.report(),
  285. " | -------"
  286. };
  287. }
  288. private static class PriorityThreadFactory implements ThreadFactory
  289. {
  290. private int _prio;
  291. private String _name;
  292. private AtomicInteger _threadNumber = new AtomicInteger(1);
  293. private ThreadGroup _group;
  294. public PriorityThreadFactory(String name, int prio)
  295. {
  296. _prio = prio;
  297. _name = name;
  298. _group = new ThreadGroup(_name);
  299. }
  300. public Thread newThread(Runnable r)
  301. {
  302. Thread t = new Thread(_group, r);
  303. t.setName(_name + "-" + _threadNumber.getAndIncrement());
  304. t.setPriority(_prio);
  305. return t;
  306. }
  307. public ThreadGroup getGroup()
  308. {
  309. return _group;
  310. }
  311. }
  312. public void shutdown()
  313. {
  314. _shutdown = true;
  315. try
  316. {
  317. _effectsScheduledThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  318. _generalScheduledThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  319. _generalPacketsThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  320. _ioPacketsThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  321. _generalThreadPool.awaitTermination(1, TimeUnit.SECONDS);
  322. _effectsScheduledThreadPool.shutdown();
  323. _generalScheduledThreadPool.shutdown();
  324. _generalPacketsThreadPool.shutdown();
  325. _ioPacketsThreadPool.shutdown();
  326. _generalThreadPool.shutdown();
  327. _log.info("All ThreadPools are now stopped");
  328. }
  329. catch (InterruptedException e)
  330. {
  331. _log.log(Level.WARNING, "", e);
  332. }
  333. }
  334. public boolean isShutdown()
  335. {
  336. return _shutdown;
  337. }
  338. public void purge()
  339. {
  340. _effectsScheduledThreadPool.purge();
  341. _generalScheduledThreadPool.purge();
  342. _aiScheduledThreadPool.purge();
  343. _ioPacketsThreadPool.purge();
  344. _generalPacketsThreadPool.purge();
  345. _generalThreadPool.purge();
  346. }
  347. public String getPacketStats()
  348. {
  349. final StringBuilder sb = new StringBuilder(1000);
  350. ThreadFactory tf = _generalPacketsThreadPool.getThreadFactory();
  351. if (tf instanceof PriorityThreadFactory)
  352. {
  353. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  354. int count = ptf.getGroup().activeCount();
  355. Thread[] threads = new Thread[count + 2];
  356. ptf.getGroup().enumerate(threads);
  357. StringUtil.append(sb, "General Packet Thread Pool:\r\n" + "Tasks in the queue: ", String.valueOf(_generalPacketsThreadPool.getQueue().size()), "\r\n"
  358. + "Showing threads stack trace:\r\n" + "There should be ", String.valueOf(count), " Threads\r\n");
  359. for (Thread t : threads)
  360. {
  361. if (t == null)
  362. continue;
  363. StringUtil.append(sb, t.getName(), "\r\n");
  364. for (StackTraceElement ste : t.getStackTrace())
  365. {
  366. StringUtil.append(sb, ste.toString(), "\r\n");
  367. }
  368. }
  369. }
  370. sb.append("Packet Tp stack traces printed.\r\n");
  371. return sb.toString();
  372. }
  373. public String getIOPacketStats()
  374. {
  375. final StringBuilder sb = new StringBuilder(1000);
  376. ThreadFactory tf = _ioPacketsThreadPool.getThreadFactory();
  377. if (tf instanceof PriorityThreadFactory)
  378. {
  379. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  380. int count = ptf.getGroup().activeCount();
  381. Thread[] threads = new Thread[count + 2];
  382. ptf.getGroup().enumerate(threads);
  383. StringUtil.append(sb, "I/O Packet Thread Pool:\r\n" + "Tasks in the queue: ", String.valueOf(_ioPacketsThreadPool.getQueue().size()), "\r\n"
  384. + "Showing threads stack trace:\r\n" + "There should be ", String.valueOf(count), " Threads\r\n");
  385. for (Thread t : threads)
  386. {
  387. if (t == null)
  388. continue;
  389. StringUtil.append(sb, t.getName(), "\r\n");
  390. for (StackTraceElement ste : t.getStackTrace())
  391. {
  392. StringUtil.append(sb, ste.toString(), "\r\n");
  393. }
  394. }
  395. }
  396. sb.append("Packet Tp stack traces printed.\r\n");
  397. return sb.toString();
  398. }
  399. public String getGeneralStats()
  400. {
  401. final StringBuilder sb = new StringBuilder(1000);
  402. ThreadFactory tf = _generalThreadPool.getThreadFactory();
  403. if (tf instanceof PriorityThreadFactory)
  404. {
  405. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  406. int count = ptf.getGroup().activeCount();
  407. Thread[] threads = new Thread[count + 2];
  408. ptf.getGroup().enumerate(threads);
  409. StringUtil.append(sb, "General Thread Pool:\r\n" + "Tasks in the queue: ", String.valueOf(_generalThreadPool.getQueue().size()), "\r\n"
  410. + "Showing threads stack trace:\r\n" + "There should be ", String.valueOf(count), " Threads\r\n");
  411. for (Thread t : threads)
  412. {
  413. if (t == null)
  414. continue;
  415. StringUtil.append(sb, t.getName(), "\r\n");
  416. for (StackTraceElement ste : t.getStackTrace())
  417. {
  418. StringUtil.append(sb, ste.toString(), "\r\n");
  419. }
  420. }
  421. }
  422. sb.append("Packet Tp stack traces printed.\r\n");
  423. return sb.toString();
  424. }
  425. private class PurgeTask implements Runnable
  426. {
  427. /* (non-Javadoc)
  428. * @see java.lang.Runnable#run()
  429. */
  430. @Override
  431. public void run()
  432. {
  433. _effectsScheduledThreadPool.purge();
  434. _generalScheduledThreadPool.purge();
  435. _aiScheduledThreadPool.purge();
  436. }
  437. }
  438. @SuppressWarnings("synthetic-access")
  439. private static class SingletonHolder
  440. {
  441. protected static final ThreadPoolManager _instance = new ThreadPoolManager();
  442. }
  443. }