content: /*
   * Copyright 2016-2020 Andres Almiray
   *
   * This file is part of Java Trove Examples
   *
   * Java Trove Examples is free software: you can redistribute it and/or modify
   * it under the terms of the GNU General Public License as published by
   * the Free Software Foundation, either version 3 of the License, or
   * (at your option) any later version.
   *
   * Java Trove Examples is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with Java Trove Examples. If not, see <http://www.gnu.org/licenses/>.
   */
  package org.kordamp.javatrove.chat03.server.impl;
  
  import javax.inject.Provider;
  import java.util.concurrent.Executors;
  import java.util.concurrent.ScheduledExecutorService;
  import java.util.concurrent.ThreadFactory;
  import java.util.concurrent.atomic.AtomicInteger;
  
  /**
   * @author Andres Almiray
   */
  public class ScheduledExecutorServiceProvider implements Provider<ScheduledExecutorService> {
      @Override
      public ScheduledExecutorService get() {
          return Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory());
      }
  
      private static class DefaultThreadFactory implements ThreadFactory {
          private static final AtomicInteger poolNumber = new AtomicInteger(1);
          private final ThreadGroup group;
          private final AtomicInteger threadNumber = new AtomicInteger(1);
          private final String namePrefix;
  
          private DefaultThreadFactory() {
              SecurityManager s = System.getSecurityManager();
              group = (s != null) ? s.getThreadGroup() :
                  Thread.currentThread().getThreadGroup();
              namePrefix = "chat-pool-" +
                  poolNumber.getAndIncrement() +
                  "-thread-";
          }
  
          public Thread newThread(Runnable r) {
              Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
              if (t.isDaemon()) { t.setDaemon(false); }
              if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); }
              return t;
          }
      }
  }
  