ThreadPoolManager.java 16 KB

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