ThreadPoolManager.java 18 KB

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