ThreadPoolManager.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. return true;
  38. }
  39. public final static void execute(Runnable task)
  40. {
  41. _mainPool.execute(task);
  42. }
  43. private static class PriorityThreadFactory implements ThreadFactory
  44. {
  45. private int _prio;
  46. private String _name;
  47. private AtomicInteger _threadNumber = new AtomicInteger(1);
  48. private ThreadGroup _group;
  49. public PriorityThreadFactory(String name, int prio)
  50. {
  51. _prio = prio;
  52. _name = name;
  53. _group = new ThreadGroup(_name);
  54. }
  55. /* (non-Javadoc)
  56. * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
  57. */
  58. public Thread newThread(Runnable r)
  59. {
  60. Thread t = new Thread(_group, r);
  61. t.setName(_name + "-" + _threadNumber.getAndIncrement());
  62. t.setPriority(_prio);
  63. return t;
  64. }
  65. public ThreadGroup getGroup()
  66. {
  67. return _group;
  68. }
  69. }
  70. }