Example usage for java.util.concurrent ThreadFactory ThreadFactory

List of usage examples for java.util.concurrent ThreadFactory ThreadFactory

Introduction

In this page you can find the example usage for java.util.concurrent ThreadFactory ThreadFactory.

Prototype

ThreadFactory

Source Link

Usage

From source file:com.azaptree.services.executor.ThreadPoolConfig.java

@NotNull
public ThreadFactory getThreadFactory() {
    if (StringUtils.isBlank(name) && !daemon) {
        return Executors.defaultThreadFactory();
    }//from   w w  w .  j a v a2 s . com

    return new ThreadFactory() {
        private final AtomicInteger threadCounter = new AtomicInteger(0);

        @Override
        public Thread newThread(final Runnable r) {
            final Thread t = new Thread(r, String.format("%s-%d", name, threadCounter.incrementAndGet()));
            t.setDaemon(daemon);
            return t;
        }
    };
}

From source file:com.netflix.iep.http.RxHttp.java

/**
 * Setup the background tasks for cleaning up connections.
 *//*from   ww w .  ja v  a2 s .c  o  m*/
@PostConstruct
public void start() {
    LOGGER.info("starting up backround cleanup threads");
    executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "spectator-rxhttp-" + NEXT_THREAD_ID.getAndIncrement());
            t.setDaemon(true);
            return t;
        }
    });

    Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                LOGGER.debug("executing cleanup for {} clients", clients.size());
                for (Map.Entry<Server, HttpClient<ByteBuf, ByteBuf>> entry : clients.entrySet()) {
                    final Server s = entry.getKey();
                    if (s.isRegistered() && !serverRegistry.isStillAvailable(s)) {
                        LOGGER.debug("cleaning up client for {}", s);
                        clients.remove(s);
                        entry.getValue().shutdown();
                    }
                }
                LOGGER.debug("cleanup complete with {} clients remaining", clients.size());
            } catch (Exception e) {
                LOGGER.warn("connection cleanup task failed", e);
            }
        }
    };

    final long cleanupFreq = Spectator.config().getLong("spectator.http.cleanupFrequency", 60);
    executor.scheduleWithFixedDelay(task, 0L, cleanupFreq, TimeUnit.SECONDS);
}

From source file:org.eclipse.gyrex.cloud.services.zookeeper.ZooKeeperBasedService.java

/**
 * Creates a new instance.//  www  .jav a2s.c  o  m
 * <p>
 * Note, this will not activate the service. Sub-classes must activate the
 * service by calling {@link #activate()} when appropriate. This can happen
 * from within the constructor (after calling this constructor using
 * <code>super(...)</code>) or lazily when active connection traction
 * becomes necessary.
 * </p>
 * 
 * @param retryDelayInMs
 *            the retry delay in milliseconds (must be greater than or equal
 *            to 50)
 * @param retryCount
 *            the number of retries to perform
 */
public ZooKeeperBasedService(final long retryDelayInMs, final int retryCount) {
    if (retryDelayInMs < 50)
        throw new IllegalArgumentException("retry delay to low");
    if (retryCount < 1)
        throw new IllegalArgumentException("retry count to low");
    this.retryDelayInMs = retryDelayInMs;
    this.retryCount = retryCount;
    executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(final Runnable r) {
            final Thread t = new Thread(r, String.format("%s Deferred Executor", ZooKeeperBasedService.this));
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(final Thread t, final Throwable e) {
                    LOG.error("Unhandled error processing operation in ({}). {}", ZooKeeperBasedService.this,
                            ExceptionUtils.getRootCauseMessage(e), e);
                }
            });
            return t;
        }
    });
}

From source file:org.opendaylight.controller.netconf.impl.ConcurrentClientsTest.java

@BeforeClass
public static void setUpClientExecutor() {
    clientExecutor = Executors.newFixedThreadPool(CONCURRENCY, new ThreadFactory() {
        int i = 1;

        @Override/*from  w  w w . j  a  v a  2s.c o m*/
        public Thread newThread(final Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("client-" + i++);
            thread.setDaemon(true);
            return thread;
        }
    });
}

From source file:org.cloudifysource.utilitydomain.admin.TimedAdmin.java

/**
 * Creates and starts a thread that monitors the admin object usage - if the object was not used for longer than 
 * the maximum idle time, the object is closed and nullified.
 *///w w  w.  j  a v a2s. co  m
private synchronized void startTimingThread() {

    // create daemon threads, so the timing thread won't keep the process alive
    executor = Executors.newSingleThreadExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
            thread.setDaemon(true);
            thread.setName("AdminTimingThread");
            return thread;
        }
    });

    executor.execute(new Runnable() {
        @Override
        public void run() {
            running = true;
            while (running) {
                try {
                    if (admin != null && (lastUsed + MAX_IDLE_TIME_MILLIS < System.currentTimeMillis())) {
                        logger.fine("Closing expired admin object");
                        admin.close();
                        admin = null;
                        running = false;
                    }
                    Thread.sleep(POLLING_INTERVAL_MILLIS);
                } catch (final InterruptedException e) {
                    // ignore
                }
            }
        }
    });

    executor.shutdown();
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private ThreadPoolExecutor createExecutor(BlockingQueue<Runnable> workQueue) {
    final AtomicInteger nextThreadNo = new AtomicInteger(0);

    final ThreadPoolExecutor executor = new ThreadPoolExecutor(//
            BenchmarkTest.THREAD_COUNT, BenchmarkTest.THREAD_COUNT, // min max threads
            0L, TimeUnit.MILLISECONDS, // the keep alive time - hold it forever
            workQueue, new ThreadFactory() {

                @Override//from w  w  w. jav a  2s . com
                public Thread newThread(Runnable r) {
                    final Thread t = new Thread(r);
                    t.setDaemon(true);
                    t.setPriority(Thread.NORM_PRIORITY);
                    t.setName("Benchmark-" + nextThreadNo.get());

                    BenchmarkTest.this.threadIds[nextThreadNo.getAndIncrement()] = t.getId();

                    return t;
                }
            });

    executor.prestartAllCoreThreads();

    return executor;
}

From source file:com.clustercontrol.agent.custom.CommandResultForwarder.java

private CommandResultForwarder() {
    {/*from   w w w .ja  va  2 s .  c  om*/
        String key = "monitor.custom.forwarding.queue.maxsize";
        int valueDefault = 5000;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _queueMaxSize = value;
    }

    {
        String key = "monitor.custom.forwarding.transport.maxsize";
        int valueDefault = 100;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportMaxSize = value;
    }

    {
        String key = "monitor.custom.forwarding.transport.maxtries";
        int valueDefault = 900;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportMaxTries = value;
    }

    {
        String key = "monitor.custom.forwarding.transport.interval.size";
        int valueDefault = 15;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportIntervalSize = value;
    }

    {
        String key = "monitor.custom.forwarding.transport.interval.msec";
        long valueDefault = 1000L;
        String str = AgentProperties.getProperty(key);
        long value = valueDefault;
        try {
            value = Long.parseLong(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportIntervalMSec = value;
    }

    _scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        private volatile int _count = 0;

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, CommandResultForwarder.class.getSimpleName() + _count++);
            t.setDaemon(true);
            return t;
        }
    });

    if (_transportIntervalMSec != -1) {
        _scheduler.scheduleWithFixedDelay(new ScheduledTask(), 0, _transportIntervalMSec,
                TimeUnit.MILLISECONDS);
    }
}

From source file:com.chicm.cmraft.core.NodeConnectionManager.java

public void collectVote(long term, long lastLogIndex, long lastLogTerm) {
    int nServers = getRemoteServers().size();
    if (nServers <= 0) {
        return;//  w w w .j  a  v  a2 s.com
    }
    ExecutorService executor = Executors.newFixedThreadPool(nServers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte) System.currentTimeMillis());
            return t;
        }
    });

    for (ServerInfo server : getRemoteServers()) {
        NodeConnection conn = connections.get(server);
        LOG.debug(getRaftNode().getName() + ": SENDING COLLECTVOTE Request TO: " + server);
        Thread t = new Thread(new AsynchronousVoteWorker(getRaftNode(), conn, getRaftNode().getServerInfo(),
                term, lastLogIndex, lastLogTerm));
        t.setDaemon(true);
        executor.execute(t);
    }
}

From source file:org.apache.bookkeeper.replication.AuditorElector.java

/**
 * AuditorElector for performing the auditor election
 *
 * @param bookieId//from   ww w.  j a  v  a  2s  .co  m
 *            - bookie identifier, comprises HostAddress:Port
 * @param conf
 *            - configuration
 * @param zkc
 *            - ZK instance
 * @param statsLogger
 *            - stats logger
 * @throws UnavailableException
 *             throws unavailable exception while initializing the elector
 */
public AuditorElector(final String bookieId, ServerConfiguration conf, ZooKeeper zkc, StatsLogger statsLogger)
        throws UnavailableException {
    this.bookieId = bookieId;
    this.conf = conf;
    this.zkc = zkc;
    this.statsLogger = statsLogger;
    this.electionAttempts = statsLogger.getCounter(ELECTION_ATTEMPTS);
    basePath = conf.getZkLedgersRootPath() + '/' + BookKeeperConstants.UNDER_REPLICATION_NODE;
    electionPath = basePath + '/' + ELECTION_ZNODE;
    createElectorPath();
    executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "AuditorElector-" + bookieId);
        }
    });
}

From source file:com.clustercontrol.agent.log.LogfileResultForwarder.java

private LogfileResultForwarder() {
    {/*from   w  w w  . jav a  2 s  .  co m*/
        String key = "monitor.logfile.forwarding.queue.maxsize";
        int valueDefault = 5000;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _queueMaxSize = value;
    }

    {
        String key = "monitor.logfile.forwarding.transport.maxsize";
        int valueDefault = 100;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportMaxSize = value;
    }

    {
        String key = "monitor.logfile.forwarding.transport.maxtries";
        int valueDefault = 900;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportMaxTries = value;
    }

    {
        String key = "monitor.logfile.forwarding.transport.interval.size";
        int valueDefault = 15;
        String str = AgentProperties.getProperty(key);
        int value = valueDefault;
        try {
            value = Integer.parseInt(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportIntervalSize = value;
    }

    {
        String key = "monitor.logfile.forwarding.transport.interval.msec";
        long valueDefault = 1000L;
        String str = AgentProperties.getProperty(key);
        long value = valueDefault;
        try {
            value = Long.parseLong(str);
            if (value != -1 && value < 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            value = valueDefault;
        } finally {
            log.info(key + " uses value \"" + value + "\". (configuration = \"" + str + "\")");
        }
        _transportIntervalMSec = value;
    }

    _scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        private volatile int _count = 0;

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, LogfileResultForwarder.class.getSimpleName() + _count++);
            t.setDaemon(true);
            return t;
        }
    });

    if (_transportIntervalMSec != -1) {
        _scheduler.scheduleWithFixedDelay(new ScheduledTask(), 0, _transportIntervalMSec,
                TimeUnit.MILLISECONDS);
    }
}