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.clustercontrol.agent.winevent.WinEventResultForwarder.java

private WinEventResultForwarder() {
    {/*ww w.j av a 2 s . co  m*/
        String key = "monitor.winevent.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.winevent.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.winevent.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.winevent.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.winevent.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, WinEventResultForwarder.class.getSimpleName() + _count++);
            t.setDaemon(true);
            return t;
        }
    });

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

From source file:co.paralleluniverse.galaxy.netty.AbstractTcpServer.java

private void configureThreadPool(String name, ThreadPoolExecutor executor) {
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
    executor.setThreadFactory(//from www  .  j ava2s .  co  m
            new ThreadFactoryBuilder().setNameFormat(name + "-%d").setThreadFactory(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    return new CommThread(r);
                }
            }).build());
    ThreadPoolExecutorMonitor.register(name, executor);
}

From source file:org.micromanager.plugins.magellan.surfacesandregions.SurfaceInterpolator.java

public SurfaceInterpolator(String xyDevice, String zDevice) {
    manager_ = SurfaceManager.getInstance();
    name_ = manager_.getNewName();/*www.j  a  va 2 s.c  o  m*/
    xyDeviceName_ = xyDevice;
    zDeviceName_ = zDevice;
    //store points sorted by z coordinate to easily find the top, for generating slice index 0 position
    points_ = new TreeSet<Point3d>(new Comparator<Point3d>() {
        @Override
        public int compare(Point3d p1, Point3d p2) {
            if (p1.z > p2.z) {
                return 1;
            } else if (p1.z < p2.z) {
                return -1;
            } else {
                if (p1.x > p2.x) {
                    return 1;
                } else if (p1.x < p2.x) {
                    return -1;
                } else {
                    if (p1.y > p2.y) {
                        return 1;
                    } else if (p1.y < p2.y) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            }
        }
    });
    mChain_ = new MonotoneChain(true);
    executor_ = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "Interpolation calculation thread ");
        }
    });
    try {
        int dir = Magellan.getCore().getFocusDirection(zDevice);
        if (dir > 0) {
            towardsSampleIsPositive_ = true;
        } else if (dir < 0) {
            towardsSampleIsPositive_ = false;
        } else {
            throw new Exception();
        }
    } catch (Exception e) {
        Log.log("Couldn't get focus direction of Z drive. Configre using Tools--Hardware Configuration Wizard");
        throw new RuntimeException();
    }

}

From source file:org.apache.http.contrib.benchmark.HttpBenchmark.java

private void execute() {

    prepare();/*from  w  ww .j  a  v  a  2 s  .  c  om*/

    ThreadPoolExecutor workerPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                public Thread newThread(Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    BenchmarkWorker[] workers = new BenchmarkWorker[threads];
    for (int i = 0; i < threads; i++) {
        workers[i] = new BenchmarkWorker(params, verbosity, request[i], host, requests, keepAlive);
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < threads) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }

    workerPool.shutdown();
    ResultProcessor.printResults(workers, host, url.toString(), contentLength);
}

From source file:org.apache.hadoop.mapreduce.v2.app.commit.CommitterEventHandler.java

@Override
protected void serviceStart() throws Exception {
    ThreadFactoryBuilder tfBuilder = new ThreadFactoryBuilder().setNameFormat("CommitterEvent Processor #%d");
    if (jobClassLoader != null) {
        // if the job classloader is enabled, we need to use the job classloader
        // as the thread context classloader (TCCL) of these threads in case the
        // committer needs to load another class via TCCL
        ThreadFactory backingTf = new ThreadFactory() {
            @Override//  ww w .  j av  a2s .c  om
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setContextClassLoader(jobClassLoader);
                return thread;
            }
        };
        tfBuilder.setThreadFactory(backingTf);
    }
    ThreadFactory tf = tfBuilder.build();
    launcherPool = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>(), tf);
    eventHandlingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            CommitterEvent event = null;
            while (!stopped.get() && !Thread.currentThread().isInterrupted()) {
                try {
                    event = eventQueue.take();
                } catch (InterruptedException e) {
                    if (!stopped.get()) {
                        LOG.error("Returning, interrupted : " + e);
                    }
                    return;
                }
                // the events from the queue are handled in parallel
                // using a thread pool
                launcherPool.execute(new EventProcessor(event));
            }
        }
    });
    eventHandlingThread.setName("CommitterEvent Handler");
    eventHandlingThread.start();
    super.serviceStart();
}

From source file:com.datatorrent.lib.io.WebSocketInputOperator.java

@Override
public void run() {
    try {/*from  ww  w .j  a  v  a  2 s. c  o  m*/
        connectionClosed = false;
        AsyncHttpClientConfigBean config = new AsyncHttpClientConfigBean();
        config.setIoThreadMultiplier(ioThreadMultiplier);
        config.setApplicationThreadPool(Executors.newCachedThreadPool(new ThreadFactory() {
            private long count = 0;

            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName(ClassUtils.getShortClassName(this.getClass()) + "-AsyncHttpClient-" + count++);
                return t;
            }

        }));

        if (client != null) {
            client.closeAsynchronously();
        }

        client = new AsyncHttpClient(config);
        connection = client.prepareGet(uri.toString()).execute(
                new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
                    @Override
                    public void onMessage(String string) {
                        LOG.debug("Got: " + string);
                        try {
                            T o = convertMessage(string);
                            if (!(skipNull && o == null)) {
                                outputPort.emit(o);
                            }
                        } catch (IOException ex) {
                            LOG.error("Got exception: ", ex);
                        }
                    }

                    @Override
                    public void onOpen(WebSocket ws) {
                        LOG.debug("Connection opened");
                    }

                    @Override
                    public void onClose(WebSocket ws) {
                        LOG.debug("Connection connectionClosed.");
                        connectionClosed = true;
                    }

                    @Override
                    public void onError(Throwable t) {
                        LOG.error("Caught exception", t);
                    }

                }).build()).get(5, TimeUnit.SECONDS);
    } catch (Exception ex) {
        LOG.error("Error reading from " + uri, ex);
        if (client != null) {
            client.close();
        }
        connectionClosed = true;
    }

}

From source file:org.apache.apex.malhar.lib.io.WebSocketInputOperator.java

@Override
public void run() {
    try {//from  www .j a  v a 2  s.co  m
        connectionClosed = false;
        AsyncHttpClientConfigBean config = new AsyncHttpClientConfigBean();
        config.setIoThreadMultiplier(ioThreadMultiplier);
        config.setApplicationThreadPool(Executors.newCachedThreadPool(new ThreadFactory() {
            private long count = 0;

            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName(ClassUtils.getShortClassName(this.getClass()) + "-AsyncHttpClient-" + count++);
                return t;
            }

        }));

        if (client != null) {
            client.closeAsynchronously();
        }

        client = new AsyncHttpClient(config);
        connection = client.prepareGet(uri.toString()).execute(
                new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
                    @Override
                    public void onMessage(String string) {
                        try {
                            T o = convertMessage(string);
                            if (!(skipNull && o == null)) {
                                outputPort.emit(o);
                            }
                        } catch (IOException ex) {
                            LOG.error("Got exception: ", ex);
                        }
                    }

                    @Override
                    public void onOpen(WebSocket ws) {
                        LOG.debug("Connection opened");
                    }

                    @Override
                    public void onClose(WebSocket ws) {
                        LOG.debug("Connection connectionClosed.");
                        connectionClosed = true;
                    }

                    @Override
                    public void onError(Throwable t) {
                        LOG.error("Caught exception", t);
                    }

                }).build()).get(5, TimeUnit.SECONDS);
    } catch (Exception ex) {
        LOG.error("Error reading from " + uri, ex);
        if (client != null) {
            client.close();
        }
        connectionClosed = true;
    }

}

From source file:disko.flow.analyzers.FullRelexAnalyzer.java

/**
 * Initialize the pool of LinkParserClients, creating CLIENT_POOL_SIZE
 * instances, which connects to ports FIRST_PORT, FIRST_PORT+1, ...,
 * FIRST_PORT+(CLIENT_POOL_SIZE-1)/* w w  w  . j av  a  2s  .c o m*/
 */
private void initializePool() throws InterruptedException {
    sentenceAlgorithmApplier = new SentenceAlgorithmApplier();
    // phraseMarkup = new PhraseMarkup();
    if (morphy == null)
        morphy = MorphyFactory.getImplementation();

    if ((hosts == null) || (hosts.size() == 0)) {
        for (int i = 0; i < DEFAULT_CLIENT_COUNT; i++) {
            addHost(DEFAULT_HOST, DEFAULT_FIRST_PORT + i);
        }
    }

    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    // +1 submission thread
    exec = Executors.newFixedThreadPool(hosts.size() + 1, new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setContextClassLoader(loader);
            t.setDaemon(true);
            return t;
        }
    });
    pool = new ArrayBlockingQueue<RelexContext>(hosts.size() + inProcessParsers);

    for (HostPort hp : hosts) {
        RemoteLGParser parser = new RemoteLGParser();
        parser.getLinkGrammarClient().setHostname(hp.host);
        parser.getLinkGrammarClient().setPort(hp.port);
        configureParser(parser);
        RelexContext context = new RelexContext(parser, morphy);
        pool.put(context);
    }

    for (int i = hosts.size(); i < pool.size(); i++) {
        LocalLGParser parser = new LocalLGParser();
        configureParser(parser);
        RelexContext context = new RelexContext(parser, morphy);
        pool.put(context);
    }
}

From source file:org.apache.hadoop.hbase.regionserver.CompactSplit.java

/** @param server */
CompactSplit(HRegionServer server) {// ww  w.j a v a2 s. c o m
    super();
    this.server = server;
    this.conf = server.getConfiguration();
    this.regionSplitLimit = conf.getInt(REGION_SERVER_REGION_SPLIT_LIMIT,
            DEFAULT_REGION_SERVER_REGION_SPLIT_LIMIT);

    int largeThreads = Math.max(1, conf.getInt(LARGE_COMPACTION_THREADS, LARGE_COMPACTION_THREADS_DEFAULT));
    int smallThreads = conf.getInt(SMALL_COMPACTION_THREADS, SMALL_COMPACTION_THREADS_DEFAULT);

    int splitThreads = conf.getInt(SPLIT_THREADS, SPLIT_THREADS_DEFAULT);

    // if we have throttle threads, make sure the user also specified size
    Preconditions.checkArgument(largeThreads > 0 && smallThreads > 0);

    final String n = Thread.currentThread().getName();

    StealJobQueue<Runnable> stealJobQueue = new StealJobQueue<>();
    this.longCompactions = new ThreadPoolExecutor(largeThreads, largeThreads, 60, TimeUnit.SECONDS,
            stealJobQueue, new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    String name = n + "-longCompactions-" + System.currentTimeMillis();
                    return new Thread(r, name);
                }
            });
    this.longCompactions.setRejectedExecutionHandler(new Rejection());
    this.longCompactions.prestartAllCoreThreads();
    this.shortCompactions = new ThreadPoolExecutor(smallThreads, smallThreads, 60, TimeUnit.SECONDS,
            stealJobQueue.getStealFromQueue(), new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    String name = n + "-shortCompactions-" + System.currentTimeMillis();
                    return new Thread(r, name);
                }
            });
    this.shortCompactions.setRejectedExecutionHandler(new Rejection());
    this.splits = (ThreadPoolExecutor) Executors.newFixedThreadPool(splitThreads, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            String name = n + "-splits-" + System.currentTimeMillis();
            return new Thread(r, name);
        }
    });
    int mergeThreads = conf.getInt(MERGE_THREADS, MERGE_THREADS_DEFAULT);
    this.mergePool = (ThreadPoolExecutor) Executors.newFixedThreadPool(mergeThreads, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            String name = n + "-merges-" + System.currentTimeMillis();
            return new Thread(r, name);
        }
    });

    // compaction throughput controller
    this.compactionThroughputController = CompactionThroughputControllerFactory.create(server, conf);
}

From source file:org.hyperic.hq.agent.server.session.AgentSynchronizer.java

@PostConstruct
void initialize() {
    this.executor = new ScheduledThreadPoolExecutor(NUM_WORKERS, new ThreadFactory() {
        private final AtomicLong i = new AtomicLong(0);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AgentSynchronizer" + i.getAndIncrement());
        }/*  w w w  .ja v a2s.  c o  m*/
    });
    log.info("starting AgentSynchronizer with " + NUM_WORKERS + " threads");
    for (int i = 0; i < NUM_WORKERS; i++) {
        SchedulerThread worker = new SchedulerThread("AgentSynchronizer" + i, i * 1000);
        executor.scheduleWithFixedDelay(worker, i + 1, NUM_WORKERS, TimeUnit.SECONDS);
    }
    concurrentStatsCollector.register(ConcurrentStatsCollector.AGENT_SYNC_JOB_QUEUE_ADDS);
    concurrentStatsCollector.register(new StatCollector() {
        public long getVal() throws StatUnreachableException {
            synchronized (agentJobs) {
                return agentJobs.size();
            }
        }

        public String getId() {
            return ConcurrentStatsCollector.AGENT_SYNCHRONIZER_QUEUE_SIZE;
        }
    });
}