ThreadPoolManager.java 17 KB

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