ThreadPoolManager.java 18 KB

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