ThreadPoolManager.java 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.communityserver.threading;
  16. import java.util.concurrent.LinkedBlockingQueue;
  17. import java.util.concurrent.ThreadFactory;
  18. import java.util.concurrent.ThreadPoolExecutor;
  19. import java.util.concurrent.TimeUnit;
  20. import java.util.concurrent.atomic.AtomicInteger;
  21. import com.l2jserver.communityserver.Config;
  22. /**
  23. * Simple wrapper class to run packets on a ThreadPoolExecutor.<br>
  24. * PriorityThreadFactory has been imported from L2J Server, coded by Wooden
  25. *
  26. * @author DrHouse - L2JServer Team
  27. *
  28. */
  29. public class ThreadPoolManager
  30. {
  31. private static ThreadPoolExecutor _mainPool;
  32. public static synchronized final boolean init()
  33. {
  34. if (_mainPool != null)
  35. return false;
  36. _mainPool = new ThreadPoolExecutor(Config.GENERAL_THREAD_CORE_SIZE, Config.GENERAL_THREAD_CORE_SIZE + 2, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new PriorityThreadFactory("CommunityServer Executor pool", Thread.NORM_PRIORITY));
  37. _mainPool.prestartAllCoreThreads();
  38. return true;
  39. }
  40. public final static void execute(Runnable task)
  41. {
  42. _mainPool.execute(task);
  43. }
  44. private static class PriorityThreadFactory implements ThreadFactory
  45. {
  46. private int _prio;
  47. private String _name;
  48. private AtomicInteger _threadNumber = new AtomicInteger(1);
  49. private ThreadGroup _group;
  50. public PriorityThreadFactory(String name, int prio)
  51. {
  52. _prio = prio;
  53. _name = name;
  54. _group = new ThreadGroup(_name);
  55. }
  56. /* (non-Javadoc)
  57. * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
  58. */
  59. public Thread newThread(Runnable r)
  60. {
  61. Thread t = new Thread(_group, r);
  62. t.setName(_name + "-" + _threadNumber.getAndIncrement());
  63. t.setPriority(_prio);
  64. return t;
  65. }
  66. @SuppressWarnings("unused")
  67. public ThreadGroup getGroup()
  68. {
  69. return _group;
  70. }
  71. }
  72. }