Example usage for java.lang Thread getName

List of usage examples for java.lang Thread getName

Introduction

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

Prototype

public final String getName() 

Source Link

Document

Returns this thread's name.

Usage

From source file:com.strategicgains.docussandra.controller.perf.remote.parent.PerfTestParent.java

public void loadData() throws IOException, ParseException, InterruptedException {
    logger.info("------------Loading Data into: " + this.getDb().name() + " with Docussandra!------------");
    ArrayList<Thread> workers = new ArrayList<>(NUM_WORKERS + 1);
    int numDocs = getNumDocuments();
    int docsPerWorker = numDocs / NUM_WORKERS;
    try {//from w ww  .  j av  a  2s .c  o  m
        List<Document> docs = getDocumentsFromFS();
        ArrayList<List<Document>> documentQueues = new ArrayList<>(NUM_WORKERS + 1);
        int numDocsAssigned = 0;
        while ((numDocsAssigned + 1) < numDocs) {
            int start = numDocsAssigned;
            int end = numDocsAssigned + docsPerWorker;
            if (end > numDocs) {
                end = numDocs - 1;
            }
            documentQueues.add(new ArrayList(docs.subList(start, end)));
            numDocsAssigned = end;
        }
        for (final List<Document> queue : documentQueues) {
            workers.add(new Thread() {
                @Override
                public void run() {
                    for (Document d : queue) {
                        //logger.debug("Processing document: " + d.toString());
                        postDocument(getDb(), getTb(), d);
                    }
                    logger.info("Thread " + Thread.currentThread().getName() + " is done.");
                }
            });
        }
    } catch (UnsupportedOperationException e)//we can't read everything in at once
    {
        //all we need to do in this block is find a way to set "workers"
        for (int i = 0; i < NUM_WORKERS; i++) {
            workers.add(new Thread() {
                private final int chunk = (int) (Math.random() * 100) + 150;//pick a random chunk so we are not going back to the FS all at the same time and potentially causing a bottle neck

                @Override
                public void run() {
                    ThreadLocal<Integer> counter = new ThreadLocal<>();
                    counter.set(new Integer(0));
                    try {
                        List<Document> docs = getDocumentsFromFS(chunk);//grab a handful of documents
                        while (docs.size() > 0) {
                            for (Document d : docs)//process the documents we grabbed
                            {
                                //logger.debug("Processing document: " + d.toString());
                                postDocument(getDb(), getTb(), d);//post them up
                                counter.set(counter.get() + 1);
                            }
                            docs = getDocumentsFromFS(chunk);//grab another handful of documents
                        }
                        logger.info("Thread " + Thread.currentThread().getName() + " is done. It processed "
                                + counter.get() + " documents.");
                    } catch (IOException | ParseException e) {
                        logger.error("Couldn't read from document", e);
                    }
                }
            });
        }
    }

    //long start = new Date().getTime();
    StopWatch sw = new StopWatch();
    sw.start();
    //start your threads!
    for (Thread t : workers) {
        t.start();
    }
    logger.info("All threads started, waiting for completion.");
    boolean allDone = false;
    boolean first = true;
    while (!allDone || first) {
        first = false;
        boolean done = true;
        for (Thread t : workers) {
            if (t.isAlive()) {
                done = false;
                logger.info("Thread " + t.getName() + " is still running.");
                break;
            }
        }
        if (done) {
            allDone = true;
            sw.stop();
        } else {
            logger.info("We still have workers running...");
            Thread.sleep(5000);
        }
    }

    long miliseconds = sw.getTime();
    double seconds = (double) miliseconds / 1000d;
    output.info("Doc: Done loading data using: " + NUM_WORKERS + " and URL: " + BASE_URI + ". Took: " + seconds
            + " seconds");
    double tpms = (double) numDocs / (double) miliseconds;
    double tps = tpms * 1000;
    double transactionTime = (double) miliseconds / (double) numDocs;
    output.info(this.getDb().name() + " Doc: Average Transactions Per Second: " + tps);
    output.info(this.getDb().name() + " Doc: Average Transactions Time (in miliseconds): " + transactionTime);
    Thread.sleep(100000);//sleep a bit to let the DB digest that before trying anything else
}

From source file:org.apache.hadoop.hbase.HBaseClusterTestCase.java

protected void threadDumpingJoin(final Thread t) {
    if (t == null) {
        return;/*from ww  w .j  av a  2s. c  o  m*/
    }
    long startTime = System.currentTimeMillis();
    while (t.isAlive()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            LOG.info("Continuing...", e);
        }
        if (System.currentTimeMillis() - startTime > 60000) {
            startTime = System.currentTimeMillis();
            ReflectionUtils.printThreadInfo(new PrintWriter(System.out),
                    "Automatic Stack Trace every 60 seconds waiting on " + t.getName());
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.WebTestCase.java

/**
 * Gets the active JavaScript threads./*w w  w  . ja  v  a 2s.  co m*/
 * @return the threads
 */
protected List<Thread> getJavaScriptThreads() {
    final Thread[] threads = new Thread[Thread.activeCount() + 10];
    Thread.enumerate(threads);
    final List<Thread> jsThreads = new ArrayList<>();
    for (final Thread t : threads) {
        if (t != null && t.getName().startsWith("JS executor for")) {
            jsThreads.add(t);
        }
    }

    return jsThreads;
}

From source file:org.powertac.visualizer.services.VisualizerServiceTournament.java

@PreDestroy
private void cleanUp() throws Exception {
    System.out.print("\nCleaning up VisualizerServiceTournament (8) : ");

    // Shutdown the proxy if needed
    if (proxy != null) {
        proxy.shutDown();/*from   w  w w .j av a2s. c  o  m*/
    }
    System.out.print("1 ");

    // Kill the tick timer
    // I have no idea why this loop is needed
    while (tickTimer == null) {
        try {
            Thread.sleep(100);
        } catch (Exception ignored) {
        }
    }
    System.out.print("2 ");

    tickTimer.cancel();
    tickTimer.purge();
    tickTimer = null;
    System.out.print("3 ");

    if (stateTask != null) {
        stateTask.cancel();
    }
    System.out.print("4 ");

    // Kill the message pump
    try {
        messageFeeder.interrupt();
        messageFeeder.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.print("5 ");

    // Kill the state machine from within
    eventQueue.clear();
    putEvent(Event.quit);
    while (runningStates) {
        try {
            Thread.sleep(100);
        } catch (Exception ignored) {
        }

        if (currentState == loginWait && stateRunner != null
                && stateRunner.getState() == Thread.State.TIMED_WAITING) {
            stateRunner.interrupt();
        }
    }
    System.out.print("6 ");

    try {
        stateRunner.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.print("7 ");

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread t : threadArray) {
        if (t.getName().contains("Timer-") || t.getName().contains("ActiveMQ")) {
            synchronized (t) {
                t.stop();
            }
        }
    }

    System.out.println("8\n");
}

From source file:org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer.java

private void enterExclusiveThread() {
    // we use simple get, check, set here, rather than CAS
    // we don't need lock-style correctness, this is only a sanity-check and we thus
    // favor speed at the cost of some false negatives in this check
    Thread previous = currentThread;
    Thread thisThread = Thread.currentThread();

    if (previous == null) {
        currentThread = thisThread;//  w ww .  j  ava 2s .  c om
    } else if (previous != thisThread) {
        throw new IllegalStateException("Concurrent access to KryoSerializer. Thread 1: " + thisThread.getName()
                + " , Thread 2: " + previous.getName());
    }
}

From source file:org.lockss.util.Logger.java

public void threadNameChanged() {
    Thread thread = Thread.currentThread();
    String name = thread.getName();
    if (!name.equals(announcedName)) {
        unannouncedName = name;//from   w w w  .  ja  v a 2s.c  o m
    }
}

From source file:org.elasticsearch.client.sniff.SnifferTests.java

public void testDefaultSchedulerThreadFactory() {
    DefaultScheduler defaultScheduler = new DefaultScheduler();
    try {/*  w w  w . j av a 2s . c  om*/
        ScheduledExecutorService executorService = defaultScheduler.executor;
        assertThat(executorService, instanceOf(ScheduledThreadPoolExecutor.class));
        assertThat(executorService, instanceOf(ScheduledThreadPoolExecutor.class));
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) executorService;
        assertTrue(executor.getRemoveOnCancelPolicy());
        assertFalse(executor.getContinueExistingPeriodicTasksAfterShutdownPolicy());
        assertTrue(executor.getExecuteExistingDelayedTasksAfterShutdownPolicy());
        assertThat(executor.getThreadFactory(), instanceOf(Sniffer.SnifferThreadFactory.class));
        int iters = randomIntBetween(3, 10);
        for (int i = 1; i <= iters; i++) {
            Thread thread = executor.getThreadFactory().newThread(new Runnable() {
                @Override
                public void run() {

                }
            });
            assertThat(thread.getName(), equalTo("es_rest_client_sniffer[T#" + i + "]"));
            assertThat(thread.isDaemon(), is(true));
        }
    } finally {
        defaultScheduler.shutdown();
    }
}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnector.java

@Override
public void run() {
    /*/*from   www  .java2  s  .c om*/
     * Accept a connection and tunnel messages through the proxy system.
     */
    Socket socket = null;
    try {
        Thread toProxyThread;
        Thread fromProxyThread;

        socket = server.accept();
        log.debug("Server accepting to socket " + socket.getInetAddress());
        Connector toProxy = new Connector(socket.getInputStream(), proxyConnection.getOutStream(), bufferSize);
        Connector fromProxy = new Connector(proxyConnection.getInStream(), socket.getOutputStream(),
                bufferSize);

        toProxyThread = new Thread(toProxy, "Client To Proxy");
        fromProxyThread = new Thread(fromProxy, "Client From Proxy");

        toProxyThread.start();
        fromProxyThread.start();

        log.debug("Waiting to finish " + toProxyThread.getName());
        toProxyThread.join();

    } catch (IOException e) {
        String errorMsg = "Problem in creating client to proxy connectors: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } catch (InterruptedException e) {
        String errorMsg = "Client to proxy communication thread interrupted: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } finally {
        if (socket != null) {
            try {
                log.debug("Closing socket " + socket.getInetAddress() + ": " + socket.getPort());
                // Also closes associated streams
                socket.close();
            } catch (IOException ex) {
                log.warn("Unable to close client to proxy socket: " + ex.getMessage());
            }
        }
        if (proxyConnection != null) {
            try {
                log.debug("Closing proxy connection " + proxyConnection.getSocket().getInetAddress() + ": "
                        + proxyConnection.getSocket().getPort());
                proxyConnection.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
        if (server != null) {
            try {
                log.debug("Closing client connection server" + server.getInetAddress() + ": "
                        + server.getLocalPort());
                server.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
    }
}

From source file:com.opentech.camel.task.BootstrapTest.java

@Before
public void before() {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override//from  w w  w .  java2  s .  c  o  m
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(String.format("Exception Thread:%s", t.getName()));
            e.printStackTrace();
        }

    });
}

From source file:ml.shifu.dtrain.DTrainRequestProcessor.java

private TailThread startTailThread(final String[] progressLog) {
    TailThread thread = new TailThread(progressLog);
    thread.setName("Tail Progress Thread");
    thread.setDaemon(true);/* w  ww  .  ja v  a 2  s .  com*/
    thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOG.warn(String.format("Error in thread %s: %s", t.getName(), e.getMessage()));
        }
    });
    thread.start();
    return thread;
}