ThreadPoolManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 net.sf.l2j.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 javolution.text.TextBuilder;
  26. import net.sf.l2j.Config;
  27. import net.sf.l2j.gameserver.network.L2GameClient;
  28. import org.mmocore.network.ReceivablePacket;
  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 net.sf.l2j.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 static ThreadPoolManager _instance;
  64. public ScheduledThreadPoolExecutor _effectsScheduledThreadPool;
  65. private ScheduledThreadPoolExecutor _generalScheduledThreadPool;
  66. private ThreadPoolExecutor _generalPacketsThreadPool;
  67. private ThreadPoolExecutor _ioPacketsThreadPool;
  68. // will be really used in the next AI implementation.
  69. private ThreadPoolExecutor _aiThreadPool;
  70. private ThreadPoolExecutor _generalThreadPool;
  71. // temp
  72. private ScheduledThreadPoolExecutor _aiScheduledThreadPool;
  73. private boolean _shutdown;
  74. public static ThreadPoolManager getInstance()
  75. {
  76. if(_instance == null)
  77. {
  78. _instance = new ThreadPoolManager();
  79. }
  80. return _instance;
  81. }
  82. private ThreadPoolManager()
  83. {
  84. _effectsScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_EFFECTS, new PriorityThreadFactory("EffectsSTPool", Thread.NORM_PRIORITY));
  85. _generalScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_GENERAL, new PriorityThreadFactory("GerenalSTPool", Thread.NORM_PRIORITY));
  86. _ioPacketsThreadPool = new ThreadPoolExecutor(Config.IO_PACKET_THREAD_CORE_SIZE, Integer.MAX_VALUE,
  87. 5L, TimeUnit.SECONDS,
  88. new LinkedBlockingQueue<Runnable>(),
  89. new PriorityThreadFactory("I/O Packet Pool",Thread.NORM_PRIORITY+1));
  90. _generalPacketsThreadPool = new ThreadPoolExecutor(Config.GENERAL_PACKET_THREAD_CORE_SIZE, Config.GENERAL_PACKET_THREAD_CORE_SIZE+2,
  91. 15L, TimeUnit.SECONDS,
  92. new LinkedBlockingQueue<Runnable>(),
  93. new PriorityThreadFactory("Normal Packet Pool",Thread.NORM_PRIORITY+1));
  94. _generalThreadPool = new ThreadPoolExecutor(Config.GENERAL_THREAD_CORE_SIZE, Config.GENERAL_THREAD_CORE_SIZE+2,
  95. 5L, TimeUnit.SECONDS,
  96. new LinkedBlockingQueue<Runnable>(),
  97. new PriorityThreadFactory("General Pool",Thread.NORM_PRIORITY));
  98. // will be really used in the next AI implementation.
  99. _aiThreadPool = new ThreadPoolExecutor(1, Config.AI_MAX_THREAD,
  100. 10L, TimeUnit.SECONDS,
  101. new LinkedBlockingQueue<Runnable>());
  102. _aiScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.AI_MAX_THREAD, new PriorityThreadFactory("AISTPool", Thread.NORM_PRIORITY));
  103. }
  104. public ScheduledFuture<?> scheduleEffect(Runnable r, long delay)
  105. {
  106. try
  107. {
  108. if (delay < 0) delay = 0;
  109. return _effectsScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  110. } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ }
  111. }
  112. public ScheduledFuture<?> scheduleEffectAtFixedRate(Runnable r, long initial, long delay)
  113. {
  114. try
  115. {
  116. if (delay < 0) delay = 0;
  117. if (initial < 0) initial = 0;
  118. return _effectsScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  119. } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ }
  120. }
  121. public ScheduledFuture<?> scheduleGeneral(Runnable r, long delay)
  122. {
  123. try
  124. {
  125. if (delay < 0) delay = 0;
  126. return _generalScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  127. } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ }
  128. }
  129. public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable r, long initial, long delay)
  130. {
  131. try
  132. {
  133. if (delay < 0) delay = 0;
  134. if (initial < 0) initial = 0;
  135. return _generalScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  136. } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ }
  137. }
  138. public ScheduledFuture<?> scheduleAi(Runnable r, long delay)
  139. {
  140. try
  141. {
  142. if (delay < 0) delay = 0;
  143. return _aiScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
  144. } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ }
  145. }
  146. public ScheduledFuture<?> scheduleAiAtFixedRate(Runnable r, long initial, long delay)
  147. {
  148. try
  149. {
  150. if (delay < 0) delay = 0;
  151. if (initial < 0) initial = 0;
  152. return _aiScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS);
  153. } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ }
  154. }
  155. public void executePacket(ReceivablePacket<L2GameClient> pkt)
  156. {
  157. _generalPacketsThreadPool.execute(pkt);
  158. }
  159. public void executeIOPacket(ReceivablePacket<L2GameClient> pkt)
  160. {
  161. _ioPacketsThreadPool.execute(pkt);
  162. }
  163. public void executeTask(Runnable r)
  164. {
  165. _generalThreadPool.execute(r);
  166. }
  167. public void executeAi(Runnable r)
  168. {
  169. _aiThreadPool.execute(r);
  170. }
  171. public String[] getStats()
  172. {
  173. return new String[] {
  174. "STP:",
  175. " + Effects:",
  176. " |- ActiveThreads: "+_effectsScheduledThreadPool.getActiveCount(),
  177. " |- getCorePoolSize: "+_effectsScheduledThreadPool.getCorePoolSize(),
  178. " |- PoolSize: "+_effectsScheduledThreadPool.getPoolSize(),
  179. " |- MaximumPoolSize: "+_effectsScheduledThreadPool.getMaximumPoolSize(),
  180. " |- CompletedTasks: "+_effectsScheduledThreadPool.getCompletedTaskCount(),
  181. " |- ScheduledTasks: "+(_effectsScheduledThreadPool.getTaskCount() - _effectsScheduledThreadPool.getCompletedTaskCount()),
  182. " | -------",
  183. " + General:",
  184. " |- ActiveThreads: "+_generalScheduledThreadPool.getActiveCount(),
  185. " |- getCorePoolSize: "+_generalScheduledThreadPool.getCorePoolSize(),
  186. " |- PoolSize: "+_generalScheduledThreadPool.getPoolSize(),
  187. " |- MaximumPoolSize: "+_generalScheduledThreadPool.getMaximumPoolSize(),
  188. " |- CompletedTasks: "+_generalScheduledThreadPool.getCompletedTaskCount(),
  189. " |- ScheduledTasks: "+(_generalScheduledThreadPool.getTaskCount() - _generalScheduledThreadPool.getCompletedTaskCount()),
  190. " | -------",
  191. " + AI:",
  192. " |- ActiveThreads: "+_aiScheduledThreadPool.getActiveCount(),
  193. " |- getCorePoolSize: "+_aiScheduledThreadPool.getCorePoolSize(),
  194. " |- PoolSize: "+_aiScheduledThreadPool.getPoolSize(),
  195. " |- MaximumPoolSize: "+_aiScheduledThreadPool.getMaximumPoolSize(),
  196. " |- CompletedTasks: "+_aiScheduledThreadPool.getCompletedTaskCount(),
  197. " |- ScheduledTasks: "+(_aiScheduledThreadPool.getTaskCount() - _aiScheduledThreadPool.getCompletedTaskCount()),
  198. "TP:",
  199. " + Packets:",
  200. " |- ActiveThreads: "+_generalPacketsThreadPool.getActiveCount(),
  201. " |- getCorePoolSize: "+_generalPacketsThreadPool.getCorePoolSize(),
  202. " |- MaximumPoolSize: "+_generalPacketsThreadPool.getMaximumPoolSize(),
  203. " |- LargestPoolSize: "+_generalPacketsThreadPool.getLargestPoolSize(),
  204. " |- PoolSize: "+_generalPacketsThreadPool.getPoolSize(),
  205. " |- CompletedTasks: "+_generalPacketsThreadPool.getCompletedTaskCount(),
  206. " |- QueuedTasks: "+_generalPacketsThreadPool.getQueue().size(),
  207. " | -------",
  208. " + I/O Packets:",
  209. " |- ActiveThreads: "+_ioPacketsThreadPool.getActiveCount(),
  210. " |- getCorePoolSize: "+_ioPacketsThreadPool.getCorePoolSize(),
  211. " |- MaximumPoolSize: "+_ioPacketsThreadPool.getMaximumPoolSize(),
  212. " |- LargestPoolSize: "+_ioPacketsThreadPool.getLargestPoolSize(),
  213. " |- PoolSize: "+_ioPacketsThreadPool.getPoolSize(),
  214. " |- CompletedTasks: "+_ioPacketsThreadPool.getCompletedTaskCount(),
  215. " |- QueuedTasks: "+_ioPacketsThreadPool.getQueue().size(),
  216. " | -------",
  217. " + General Tasks:",
  218. " |- ActiveThreads: "+_generalThreadPool.getActiveCount(),
  219. " |- getCorePoolSize: "+_generalThreadPool.getCorePoolSize(),
  220. " |- MaximumPoolSize: "+_generalThreadPool.getMaximumPoolSize(),
  221. " |- LargestPoolSize: "+_generalThreadPool.getLargestPoolSize(),
  222. " |- PoolSize: "+_generalThreadPool.getPoolSize(),
  223. " |- CompletedTasks: "+_generalThreadPool.getCompletedTaskCount(),
  224. " |- QueuedTasks: "+_generalThreadPool.getQueue().size(),
  225. " | -------",
  226. " + AI:",
  227. " |- Not Done"
  228. };
  229. }
  230. private class PriorityThreadFactory implements ThreadFactory
  231. {
  232. private int _prio;
  233. private String _name;
  234. private AtomicInteger _threadNumber = new AtomicInteger(1);
  235. private ThreadGroup _group;
  236. public PriorityThreadFactory(String name, int prio)
  237. {
  238. _prio = prio;
  239. _name = name;
  240. _group = new ThreadGroup(_name);
  241. }
  242. /* (non-Javadoc)
  243. * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
  244. */
  245. public Thread newThread(Runnable r)
  246. {
  247. Thread t = new Thread(_group,r);
  248. t.setName(_name+"-"+_threadNumber.getAndIncrement());
  249. t.setPriority(_prio);
  250. return t;
  251. }
  252. public ThreadGroup getGroup()
  253. {
  254. return _group;
  255. }
  256. }
  257. /**
  258. *
  259. */
  260. public void shutdown()
  261. {
  262. _shutdown = true;
  263. try
  264. {
  265. _effectsScheduledThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  266. _generalScheduledThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  267. _generalPacketsThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  268. _ioPacketsThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  269. _generalThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  270. _aiThreadPool.awaitTermination(1,TimeUnit.SECONDS);
  271. _effectsScheduledThreadPool.shutdown();
  272. _generalScheduledThreadPool.shutdown();
  273. _generalPacketsThreadPool.shutdown();
  274. _ioPacketsThreadPool.shutdown();
  275. _generalThreadPool.shutdown();
  276. _aiThreadPool.shutdown();
  277. _log.info("All ThreadPools are now stoped");
  278. }
  279. catch (InterruptedException e)
  280. {
  281. // TODO Auto-generated catch block
  282. e.printStackTrace();
  283. }
  284. }
  285. public boolean isShutdown()
  286. {
  287. return _shutdown;
  288. }
  289. /**
  290. *
  291. */
  292. public void purge()
  293. {
  294. _effectsScheduledThreadPool.purge();
  295. _generalScheduledThreadPool.purge();
  296. _aiScheduledThreadPool.purge();
  297. _ioPacketsThreadPool.purge();
  298. _generalPacketsThreadPool.purge();
  299. _generalThreadPool.purge();
  300. _aiThreadPool.purge();
  301. }
  302. /**
  303. *
  304. */
  305. public String getPacketStats()
  306. {
  307. TextBuilder tb = new TextBuilder();
  308. ThreadFactory tf = _generalPacketsThreadPool.getThreadFactory();
  309. if (tf instanceof PriorityThreadFactory)
  310. {
  311. tb.append("General Packet Thread Pool:\r\n");
  312. tb.append("Tasks in the queue: "+_generalPacketsThreadPool.getQueue().size()+"\r\n");
  313. tb.append("Showing threads stack trace:\r\n");
  314. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  315. int count = ptf.getGroup().activeCount();
  316. Thread[] threads = new Thread[count+2];
  317. ptf.getGroup().enumerate(threads);
  318. tb.append("There should be "+count+" Threads\r\n");
  319. for(Thread t : threads)
  320. {
  321. if(t == null)
  322. continue;
  323. tb.append(t.getName()+"\r\n");
  324. for(StackTraceElement ste :t.getStackTrace())
  325. {
  326. tb.append(ste.toString());
  327. tb.append("\r\n");
  328. }
  329. }
  330. }
  331. tb.append("Packet Tp stack traces printed.\r\n");
  332. return tb.toString();
  333. }
  334. public String getIOPacketStats()
  335. {
  336. TextBuilder tb = new TextBuilder();
  337. ThreadFactory tf = _ioPacketsThreadPool.getThreadFactory();
  338. if (tf instanceof PriorityThreadFactory)
  339. {
  340. tb.append("I/O Packet Thread Pool:\r\n");
  341. tb.append("Tasks in the queue: "+_ioPacketsThreadPool.getQueue().size()+"\r\n");
  342. tb.append("Showing threads stack trace:\r\n");
  343. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  344. int count = ptf.getGroup().activeCount();
  345. Thread[] threads = new Thread[count+2];
  346. ptf.getGroup().enumerate(threads);
  347. tb.append("There should be "+count+" Threads\r\n");
  348. for(Thread t : threads)
  349. {
  350. if(t == null)
  351. continue;
  352. tb.append(t.getName()+"\r\n");
  353. for(StackTraceElement ste :t.getStackTrace())
  354. {
  355. tb.append(ste.toString());
  356. tb.append("\r\n");
  357. }
  358. }
  359. }
  360. tb.append("Packet Tp stack traces printed.\r\n");
  361. return tb.toString();
  362. }
  363. public String getGeneralStats()
  364. {
  365. TextBuilder tb = new TextBuilder();
  366. ThreadFactory tf = _generalThreadPool.getThreadFactory();
  367. if (tf instanceof PriorityThreadFactory)
  368. {
  369. tb.append("General Thread Pool:\r\n");
  370. tb.append("Tasks in the queue: "+_generalThreadPool.getQueue().size()+"\r\n");
  371. tb.append("Showing threads stack trace:\r\n");
  372. PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
  373. int count = ptf.getGroup().activeCount();
  374. Thread[] threads = new Thread[count+2];
  375. ptf.getGroup().enumerate(threads);
  376. tb.append("There should be "+count+" Threads\r\n");
  377. for(Thread t : threads)
  378. {
  379. if(t == null)
  380. continue;
  381. tb.append(t.getName()+"\r\n");
  382. for(StackTraceElement ste :t.getStackTrace())
  383. {
  384. tb.append(ste.toString());
  385. tb.append("\r\n");
  386. }
  387. }
  388. }
  389. tb.append("Packet Tp stack traces printed.\r\n");
  390. return tb.toString();
  391. }
  392. }