ThreadPoolManager.java 18 KB

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