Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

In this page you can find the example usage for java.lang Thread setName.

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:org.apache.synapse.aspects.flow.statistics.log.StatisticEventProcessor.java

public static void initializeCleaningThread() {
    //Thread to consume queue and update data structures for publishing
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Mediation Statistic Stale Entry Cleaning Task");
            return t;
        }//from w ww. j ava2  s .  com
    });
    Long eventCleanTime = Long.parseLong(
            SynapsePropertiesLoader.getPropertyValue(StatisticsConstants.FLOW_STATISTICS_EVENT_CLEAN_TIME,
                    StatisticsConstants.FLOW_STATISTICS_DEFAULT_EVENT_CLEAN_INTERVAL));
    StatisticCleaningThread statisticCleaningThread = new StatisticCleaningThread(runtimeStatistics);
    executor.scheduleAtFixedRate(statisticCleaningThread, 0, eventCleanTime, TimeUnit.MILLISECONDS);
}

From source file:Test.java

private static void startUpdateThread(int i, final ConcurrentMap<Integer, String> concurrentMap) {
    Thread thread = new Thread(new Runnable() {
        public void run() {
            while (!Thread.interrupted()) {
                Random random = new Random();
                int randomInt = random.nextInt(20);
                concurrentMap.put(randomInt, UUID.randomUUID().toString());
            }//from   w  w w.  j a  v  a 2  s.c o  m
        }
    });
    thread.setName("Update Thread " + i);
    updateThreads.add(thread);
    thread.start();
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerUtil.java

/**
 * Creates a {@link ScheduledThreadPoolExecutor} for use on {@link LogsDownloaderWorker}.
 * //from  w  w  w  . j  av a2  s.co  m
 * @param caller
 * @return
 */
static ScheduledThreadPoolExecutor createThreadPool(LogsDownloaderWorker caller) {
    ScheduledThreadPoolExecutor ret = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(4,
            new ThreadFactory() {
                private ThreadGroup group;
                private long count = 0;
                {
                    SecurityManager s = System.getSecurityManager();
                    group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
                }

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(group, r);
                    t.setName(caller.getClass().getSimpleName() + "::" + Integer.toHexString(caller.hashCode())
                            + "::" + count++);
                    t.setDaemon(true);
                    return t;
                }
            });

    return ret;
}

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//  www .java 2 s  .  c  om
        public Thread newThread(final Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("client-" + i++);
            thread.setDaemon(true);
            return thread;
        }
    });
}

From source file:com.offbynull.voip.ui.UiWebRegion.java

public static UiWebRegion create(Bus busFromGateway, Bus busToGateway) {
    UiWebRegion ret = new UiWebRegion(busFromGateway, busToGateway);

    URL resource = ret.getClass().getResource("/index.html");
    Validate.validState(resource != null); // should never happen, sanity check

    String mainPageLink = resource.toExternalForm();

    ret.webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
        if (newState == State.SUCCEEDED) {
            JSObject win = (JSObject) ret.webEngine.executeScript("window");
            win.setMember("messageSender", ret.new JavascriptToGatewayBridge());

            busToGateway.add(new UiAction(new ReadyAction(false)));
        } else if (newState == State.CANCELLED || newState == State.FAILED) {
            busToGateway.add(new UiAction(new ReadyAction(true)));
        }//from w  ww  .  j a va  2  s . com
    });
    ret.webEngine.load(mainPageLink);

    // This block makes sure to kill the incoming message pump if this webregion is removed from its parent, and (re)starts it if its
    // added
    //
    // NOTE: CANNOT USE PARENTPROPERTY -- PARENTPROPERTY ALWAYS RETURNS NULL FOR WHATEVER REASON
    ret.sceneProperty().addListener((observable, oldValue, newValue) -> {
        ret.lock.lock();
        try {
            if (oldValue != null) {
                ret.incomingMessagePumpThread.interrupt();
                ret.incomingMessagePumpThread.join();
                ret.incomingMessagePumpThread = null;
            }

            if (newValue != null) {
                Thread thread = new Thread(ret.new GatewayToJavascriptPump());
                thread.setDaemon(true);
                thread.setName(UiWebRegion.class.getSimpleName() + "-GatewayToJavascriptPump");
                thread.start();
                ret.incomingMessagePumpThread = thread;
            }
        } catch (InterruptedException ex) {
            throw new IllegalStateException(ex);
        } finally {
            ret.lock.unlock();
        }
    });

    return ret;
}

From source file:org.normandra.CassandraTestUtil.java

public static void start(final String yamlFile) throws Exception {
    if (embedded != null) {
        return;/*  w  ww .  j  av  a2  s  . c o  m*/
    }

    log4j(false);

    final File embeddedDir = new File("target/embeddedCassandra").getCanonicalFile();
    final File tmpYaml = new File(embeddedDir, FilenameUtils.getName(yamlFile));
    if (tmpYaml.exists()) {
        FileUtils.forceDelete(tmpYaml);
    }
    if (embeddedDir.exists()) {
        FileUtils.deleteDirectory(embeddedDir);
    }
    FileUtils.copyURLToFile(CassandraTestUtil.class.getResource(yamlFile), tmpYaml);

    System.setProperty("cassandra.config", tmpYaml.getCanonicalFile().toURI().toString());
    System.setProperty("cassandra-foreground", "true");

    clearAndReset();

    if (null == embedded) {
        final AtomicBoolean started = new AtomicBoolean(false);
        embedded = new EmbeddedCassandraService();
        final Runnable worker = new Runnable() {
            @Override
            public void run() {
                try {
                    embedded.start();
                    started.getAndSet(true);
                } catch (final Exception e) {
                    logger.warn("Unable to start embedded cassandra server.", e);
                }
            }
        };
        final Thread thread = new Thread(worker);
        thread.setDaemon(true);
        thread.setName(CassandraTestUtil.class.getSimpleName() + "[embedded]");
        thread.start();

        for (int i = 0; i < 60; i++) {
            if (started.get()) {
                break;
            }
            Thread.sleep(250);
        }
    }
}

From source file:at.ac.ait.ubicity.fileloader.FileLoader.java

/**
 * /*from w ww.j  a va  2s .  c om*/
 * @param _fileInfo A FileInformation object representing usage information on the file we are supposed to load: line count already ingested, last usage time...
 * @param _keySpace Cassandra key space into which to ingest
 * @param _host Cassandra host / server
 * @param _batchSize MutationBatch size
 * @throws Exception Shouldn't happen, although the Disruptor may throw an Exception under duress
 */
@SuppressWarnings("unchecked")
public final static void load(final FileInformation _fileInfo, final String _keySpace, final String _host,
        final int _batchSize) throws Exception {

    if (!cassandraInitialized) {
        keySpace = AstyanaxInitializer.doInit("Test Cluster", _host, _keySpace);
        cassandraInitialized = true;
    }

    LongTimeStampSorter tsSorter = new LongTimeStampSorter();
    Thread tTSSorter = new Thread(tsSorter);
    tTSSorter.setPriority(Thread.MAX_PRIORITY - 1);
    tTSSorter.setName("long timestamp sorter ");
    tTSSorter.start();
    //get the log id from the file's URI
    final String log_id = _fileInfo.getURI().toString();

    final MutationBatch batch = keySpace.prepareMutationBatch();

    logger.info("got keyspace " + keySpace.getKeyspaceName() + " from Astyanax initializer");

    final LineIterator onLines = FileUtils.lineIterator(new File(_fileInfo.getURI()));

    final ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    ColumnFamily crawl_stats = null;

    AggregationJob aggregationJob = new AggregationJob(keySpace, crawl_stats);
    Thread tAggJob = new Thread(aggregationJob);
    tAggJob.setName("Monitrix loader / aggregation job ");
    tAggJob.setPriority(Thread.MIN_PRIORITY + 1);
    tAggJob.start();
    logger.info("[FILELOADER] started aggregation job, ring buffer running");

    final Disruptor<SingleLogLineAsString> disruptor = new Disruptor(SingleLogLineAsString.EVENT_FACTORY,
            (int) Math.pow(TWO, 17), exec);
    SingleLogLineAsStringEventHandler.batch = batch;
    SingleLogLineAsStringEventHandler.keySpace = keySpace;
    SingleLogLineAsStringEventHandler.batchSize = _batchSize;
    SingleLogLineAsStringEventHandler.LOG_ID = log_id;
    SingleLogLineAsStringEventHandler.tsSorter = tsSorter;
    SingleLogLineAsStringEventHandler.aggregationJob = aggregationJob;

    //The EventHandler contains the actual logic for ingesting
    final EventHandler<SingleLogLineAsString> handler = new SingleLogLineAsStringEventHandler();

    disruptor.handleEventsWith(handler);

    //get our Aggregate job in place

    //we are almost ready to start
    final RingBuffer<SingleLogLineAsString> rb = disruptor.start();

    int _lineCount = 0;
    long _start, _lapse;
    _start = System.nanoTime();

    int _linesAlreadyProcessed = _fileInfo.getLineCount();

    //cycle through the lines already processed
    while (_lineCount < _linesAlreadyProcessed) {
        onLines.nextLine();
        _lineCount++;
    }

    //now get down to the work we actually must do, and fill the ring buffer
    logger.info("begin proccessing of file " + _fileInfo.getURI() + " @line #" + _lineCount);
    while (onLines.hasNext()) {

        final long _seq = rb.next();
        final SingleLogLineAsString event = rb.get(_seq);
        event.setValue(onLines.nextLine());
        rb.publish(_seq);
        _lineCount++;
    }
    _lapse = System.nanoTime() - _start;
    logger.info("ended proccessing of file " + _fileInfo.getURI() + " @line #" + _lineCount);

    //stop, waiting for last threads still busy to finish their work
    disruptor.shutdown();

    //update the file info, this will  land in the cache
    _fileInfo.setLineCount(_lineCount);
    _fileInfo.setLastAccess(System.currentTimeMillis());
    int _usageCount = _fileInfo.getUsageCount();
    _fileInfo.setUsageCount(_usageCount++);

    //make sure we release resources
    onLines.close();

    logger.info(
            "handled " + (_lineCount - _linesAlreadyProcessed) + " log lines in " + _lapse + " nanoseconds");

    //now go to aggregation step
    SortedSet<Long> timeStamps = new TreeSet(tsSorter.timeStamps);

    long _minTs = timeStamps.first();
    long _maxTs = timeStamps.last();
    logger.info("**** min TimeStamp = " + _minTs);
    logger.info("**** max TimeStamp = " + _maxTs);

    StatsTableActualizer.update(_fileInfo.getURI().toString(), _minTs, _maxTs, _lineCount);

    //        AggregationJob aggJob = new AggregationJob( keySpace, _host, _batchSize );
    //        Thread tAgg = new Thread( aggJob );
    //        tAgg.setName( "aggregation job " );
    //        tAgg.setPriority( Thread.MAX_PRIORITY - 1 );
    //        tAgg.start();

}

From source file:com.asprise.imaging.core.Imaging.java

/** Use this executor service to make sure that all scanning related code is executed from the same thread. */
public static ExecutorService getDefaultExecutorServiceForScanning() {
    if (executorServiceForScanning == null) {
        synchronized (Imaging.class) {
            if (executorServiceForScanning == null) {
                executorServiceForScanning = Executors.newSingleThreadExecutor(new ThreadFactory() { // custom factory for user-friendly thread name
                    final AtomicInteger threadNumber = new AtomicInteger(1);
                    ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();

                    @Override/*from w ww .  jav a  2  s .  c o m*/
                    public Thread newThread(Runnable r) {
                        Thread thread = defaultThreadFactory.newThread(r);
                        thread.setName("scan" + (threadNumber.get() == 1 ? "" : "-" + threadNumber));
                        return thread;
                    }
                });
            }
        }
    }
    return executorServiceForScanning;
}

From source file:org.gtdfree.ApplicationHelper.java

public static synchronized void executeInBackground(Runnable r) {

    if (backgroundExecutor == null) {
        backgroundExecutor = new ThreadPoolExecutor(0, 1, 1, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                    @Override//from  w w w. j  av a  2  s  . c o  m
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setName("BackgroundExecutor"); //$NON-NLS-1$
                        t.setPriority(Thread.MIN_PRIORITY);
                        t.setDaemon(false);
                        return t;
                    }
                });
    }

    backgroundExecutor.execute(r);

}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Method used to run a multi-threaded benchmark.
 *
 * @param method to measure// w  w w. j a v a  2 s . com
 * @param path path to store benchmarking test data
 * @param iterations number of iterations to run
 * @param concurrency number of threads to run
 * @throws IOException thrown when we can't communicate with the server
 */
private static void multithreadedBenchmark(final String method, final String path, final int iterations,
        final int concurrency) throws IOException {
    final AtomicLong fullAggregation = new AtomicLong(0L);
    final AtomicLong serverAggregation = new AtomicLong(0L);
    final AtomicLong count = new AtomicLong(0L);
    final long perThreadCount = perThreadCount(iterations, concurrency);

    System.out.printf("Running %d iterations per thread\n", perThreadCount);

    final long testStart = System.nanoTime();

    Runtime.getRuntime().addShutdownHook(new Thread(Benchmark::cleanUp));

    final Callable<Void> worker = () -> {
        for (int i = 0; i < perThreadCount; i++) {
            Duration[] durations;

            if (method.equals("put")) {
                durations = measurePut(sizeInBytesOrNoOfDirs);
            } else if (method.equals("putDir")) {
                durations = measurePutDir(sizeInBytesOrNoOfDirs);
            } else {
                durations = measureGet(path);
            }

            long fullLatency = durations[0].toMillis();
            long serverLatency = durations[1].toMillis();
            fullAggregation.addAndGet(fullLatency);
            serverAggregation.addAndGet(serverLatency);

            System.out.printf("%s %d full=%dms, server=%dms, thread=%s\n", method, count.getAndIncrement(),
                    fullLatency, serverLatency, Thread.currentThread().getName());
        }

        return null;
    };

    final Thread.UncaughtExceptionHandler handler = (t, e) -> LOG.error("Error when executing benchmark", e);

    final AtomicInteger threadCounter = new AtomicInteger(0);
    ThreadFactory threadFactory = r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setUncaughtExceptionHandler(handler);
        t.setName(String.format("benchmark-%d", threadCounter.incrementAndGet()));

        return t;
    };

    ExecutorService executor = Executors.newFixedThreadPool(concurrency, threadFactory);

    List<Callable<Void>> workers = new ArrayList<>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        workers.add(worker);
    }

    try {
        List<Future<Void>> futures = executor.invokeAll(workers);

        boolean completed = false;
        while (!completed) {
            try (Stream<Future<Void>> stream = futures.stream()) {
                completed = stream.allMatch((f) -> f.isDone() || f.isCancelled());

                if (!completed) {
                    Thread.sleep(CHECK_INTERVAL);
                }
            }
        }

    } catch (InterruptedException e) {
        return;
    } finally {
        System.err.println("Shutting down the thread pool");
        executor.shutdown();
    }

    final long testEnd = System.nanoTime();

    final long fullAverage = Math.round(fullAggregation.get() / iterations);
    final long serverAverage = Math.round(serverAggregation.get() / iterations);
    final long totalTime = Duration.ofNanos(testEnd - testStart).toMillis();

    System.out.printf("Average full latency: %d ms\n", fullAverage);
    System.out.printf("Average server latency: %d ms\n", serverAverage);
    System.out.printf("Total test time: %d ms\n", totalTime);
    System.out.printf("Total invocations: %d\n", count.get());
}