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:pl.otros.logview.exceptionshandler.ShowErrorDialogExceptionHandler.java

@Override
protected void uncaughtExceptionInSwingEDT(Thread thread, Throwable throwable) {
    String stackTraceAsString = Throwables.getStackTraceAsString(throwable);
    if (caughtStackTraces.contains(stackTraceAsString)) {
        LOGGER.info("Not sending the same error report twice");
        return;/*from  w  ww.j  ava2  s .c o m*/
    }
    caughtStackTraces.add(stackTraceAsString);
    JPanel message = new JPanel(new BorderLayout());
    message.add(new JLabel("Error in thread " + thread.getName()), BorderLayout.NORTH);

    String stackTrace = getStackTrace(throwable);
    JTextArea textArea = new JTextArea(10, 70);
    textArea.setText(stackTrace);
    textArea.setCaretPosition(0);
    message.add(new JScrollPane(textArea));

    JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);

    Map<String, String> errorReportData = generateReportData(thread, throwable, otrosApplication);
    JComponent jComponent = createDialogView();
    String[] options = { "Send", "Do not send" };
    int sendReport = JOptionPane.showOptionDialog(otrosApplication.getApplicationJFrame(), jComponent,
            "Send error report confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
            Icons.MEGAPHONE_24, options, options[0]);
    errorReportData.put("USER:email", emailTextField.getText());
    errorReportData.put("USER:comment", commentTextArea.getText());

    if (sendReport == JOptionPane.YES_OPTION) {
        DataConfiguration c = otrosApplication.getConfiguration();
        c.setProperty(ConfKeys.HTTP_PROXY_USE, checkBoxUseProxy.isSelected());
        c.setProperty(ConfKeys.HTTP_PROXY_HOST, proxyTf.getText());
        c.setProperty(ConfKeys.HTTP_PROXY_PORT, proxyPortModel.getNumber().intValue());
        c.setProperty(ConfKeys.HTTP_PROXY_USER, proxyUser.getText());
        sendReportInNewBackground(errorReportData);
    } else {
        LOGGER.info("Not sending error report");
    }

    logErrorReport(errorReportData);

}

From source file:org.nd4j.linalg.jcublas.context.ContextHolder.java

/**
 * Configure the given information//  w  w w.j  a v a2  s  . co  m
 * based on the device
 */
public void configure() {
    if (confCalled)
        return;

    JCublas2.setExceptionsEnabled(true);
    JCudaDriver.setExceptionsEnabled(true);
    JCuda.setExceptionsEnabled(true);

    if (deviceSetup.get())
        return;

    JCudaDriver.cuInit(0);
    int count[] = new int[1];
    cuDeviceGetCount(count);
    numDevices = count[0];
    log.debug("Found " + numDevices + " gpus");

    if (numDevices < 1)
        numDevices = 1;
    bannedDevices = new ArrayList<>();

    String props = System.getProperty(DEVICES_TO_BAN, "-1");
    String[] split = props.split(",");
    //Should only be used in multi device scenarios; otherwise always use one device
    if (split.length >= 1)
        for (String s : split) {
            Integer i = Integer.parseInt(s);
            if (i >= 0)
                bannedDevices.add(Integer.parseInt(s));

        }

    deviceSetup.set(true);
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

    for (int i = 0; i < numDevices; i++) {
        for (Thread thread : threadSet)
            getContext(i, thread.getName());
    }

    setContext();

    try {
        KernelFunctionLoader.getInstance().load();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Check if the device supports mapped host memory
    cudaDeviceProp deviceProperties = new cudaDeviceProp();
    JCuda.cudaGetDeviceProperties(deviceProperties, 0);
    if (deviceProperties.canMapHostMemory == 0) {
        System.err.println("This device can not map host memory");
        System.err.println(deviceProperties.toFormattedString());
        return;
    }

    //force certain ops to have a certain number of threads
    Properties threadProps = new Properties();
    try {
        InputStream is = ContextHolder.class.getResourceAsStream("/function_threads.properties");
        threadProps.load(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String prop : threadProps.stringPropertyNames()) {
        threads.put(prop, Integer.parseInt(threadProps.getProperty(prop)));
    }

    try {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setJmxEnabled(true);
        config.setBlockWhenExhausted(false);
        config.setMaxIdle(Runtime.getRuntime().availableProcessors());
        config.setMaxTotal(Runtime.getRuntime().availableProcessors());
        config.setMinIdle(Runtime.getRuntime().availableProcessors());
        config.setJmxNameBase("handles");
        handlePool = new CublasHandlePool(new CublasHandlePooledItemFactory(), config);
        GenericObjectPoolConfig confClone = config.clone();
        confClone.setMaxTotal(Runtime.getRuntime().availableProcessors() * 10);
        confClone.setMaxIdle(Runtime.getRuntime().availableProcessors() * 10);
        confClone.setMinIdle(Runtime.getRuntime().availableProcessors() * 10);
        GenericObjectPoolConfig streamConf = confClone.clone();
        streamConf.setJmxNameBase("streams");
        streamPool = new StreamPool(new StreamItemFactory(), streamConf);
        GenericObjectPoolConfig oldStreamConf = streamConf.clone();
        oldStreamConf.setJmxNameBase("oldstream");
        oldStreamPool = new OldStreamPool(new OldStreamItemFactory(), oldStreamConf);
        setContext();
        //seed with multiple streams to encourage parallelism
        for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
            streamPool.addObject();
            oldStreamPool.addObject();
        }

        //force context initialization to occur
        JCuda.cudaFree(Pointer.to(new int[] { 0 }));

    } catch (Exception e) {
        log.warn("Unable to initialize cuda", e);
    }

    for (int i = 0; i < numDevices; i++) {
        ClassPathResource confFile = new ClassPathResource("devices/" + i,
                ContextHolder.class.getClassLoader());
        if (confFile.exists()) {
            Properties props2 = new Properties();
            try {
                props2.load(confFile.getInputStream());
                confs.put(i, new DeviceConfiguration(i, props2));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else
            confs.put(i, new DeviceConfiguration(i));

    }

    confCalled = true;
}

From source file:net.minecraftforge.fml.common.FMLCommonHandler.java

/**
 * Return the effective side for the context in the game. This is dependent
 * on thread analysis to try and determine whether the code is running in the
 * server or not. Use at your own risk/*from  w w w .ja v a 2 s .  c om*/
 */
public Side getEffectiveSide() {
    Thread thr = Thread.currentThread();
    if (thr.getName().equals("Server thread") || thr.getName().startsWith("Netty Server IO")) {
        return Side.SERVER;
    }

    return Side.CLIENT;
}

From source file:org.apache.hadoop.hbase.master.cleaner.HFileCleaner.java

/**
 * Start threads for hfile deletion//from  w w w. ja  va 2s.  c  o  m
 */
private void startHFileDeleteThreads() {
    final String n = Thread.currentThread().getName();
    running = true;
    // start thread for large file deletion
    Thread large = new Thread() {
        @Override
        public void run() {
            consumerLoop(largeFileQueue);
        }
    };
    large.setDaemon(true);
    large.setName(n + "-HFileCleaner.large-" + System.currentTimeMillis());
    large.start();
    LOG.debug("Starting hfile cleaner for large files: " + large.getName());
    threads.add(large);

    // start thread for small file deletion
    Thread small = new Thread() {
        @Override
        public void run() {
            consumerLoop(smallFileQueue);
        }
    };
    small.setDaemon(true);
    small.setName(n + "-HFileCleaner.small-" + System.currentTimeMillis());
    small.start();
    LOG.debug("Starting hfile cleaner for small files: " + small.getName());
    threads.add(small);
}

From source file:org.openmrs.util.OpenmrsClassLoader.java

public static void onShutdown() {

    //Since we are shutting down, stop all threads that reference the openmrs class loader.
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread thread : threadArray) {

        ClassLoader classLoader = thread.getContextClassLoader();

        //Threads like Finalizer, Reference Handler, etc have null class loader reference.
        if (classLoader == null) {
            continue;
        }/*from   w  w w  . java  2s . c o m*/

        if (classLoader instanceof OpenmrsClassLoader) {
            try {
                //Set to WebappClassLoader just in case stopping fails.
                thread.setContextClassLoader(classLoader.getParent());

                //Stopping the current thread will halt all current cleanup.
                //So do not ever ever even attempt stopping it. :)
                if (thread == Thread.currentThread()) {
                    continue;
                }

                log.info("onShutdown Stopping thread: " + thread.getName());
                thread.stop();
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }

    clearReferences();
}

From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

private Thread findServerMainThread() {
    Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
    for (Thread th : map.keySet()) {
        if (th.getName().equals(SERVER_THREAD_NAME)) {
            return th;
        }/*  w  w  w .java 2s .  com*/
    }
    return null;
}

From source file:com.thoughtworks.go.server.service.PipelineConfigServicePerformanceTest.java

private void run(Runnable runnable, int numberOfRequests, final ConcurrentHashMap<String, Boolean> results)
        throws InterruptedException {
    Boolean finalResult = true;/*from   w  ww .  j  a va 2  s  .c  om*/
    LOGGER.info("Tests start now!");
    final ArrayList<Thread> threads = new ArrayList<>();
    for (int i = 0; i < numberOfRequests; i++) {
        Thread t = new Thread(runnable, "pipeline" + i);
        threads.add(t);
    }
    for (Thread t : threads) {
        Thread.sleep(1000 * (new Random().nextInt(3) + 1));
        t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                LOGGER.error("Exception " + e + " from thread " + t);
                results.put(t.getName(), false);
            }
        });
        t.start();
    }
    for (Thread t : threads) {
        int i = threads.indexOf(t);
        if (i == (numberOfRequests - 1)) {
            //                takeHeapDump(dumpDir, i);
        }
        t.join();
    }
    for (String threadId : results.keySet()) {
        finalResult = results.get(threadId) && finalResult;
    }
    assertThat(finalResult, is(true));
}

From source file:org.ut.biolab.medsavant.MedSavantServlet.java

private void setExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from w  w  w .j a v a  2  s .  c om
        public void uncaughtException(Thread t, Throwable e) {
            LOG.info("Global exception handler caught: " + t.getName() + ": " + e);

            if (e instanceof InvocationTargetException) {
                e = ((InvocationTargetException) e).getCause();
            }

            if (e instanceof SessionExpiredException) {
                SessionExpiredException see = (SessionExpiredException) e;
                LOG.error("Session expired exception: " + see.toString());
                return;
            }
            e.printStackTrace();
        }
    });
}

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

@SuppressWarnings("deprecation")
private static void clearReferencesThreads(ClassLoader classLoader) {
    Thread[] threads = getThreads();

    // Iterate over the set of threads
    for (Thread thread : threads) {
        if (thread != null) {
            ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl == classLoader) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }/*w  w  w .  j a v  a2  s . c o m*/

                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                // Don't warn about JVM controlled threads
                ThreadGroup tg = thread.getThreadGroup();
                if (tg != null && JVM_THREAD_GROUP_NAMES.contains(tg.getName())) {
                    continue;
                }

                // TimerThread is not normally visible
                if (thread.getClass().getName().equals("java.util.TimerThread")) {
                    clearReferencesStopTimerThread(thread);
                    continue;
                }

                if (logger.isLoggable(Level.FINE))
                    logger.fine("A thread named [" + thread.getName()
                            + "] started but has failed to stop it. This is very likely to create a memory leak.");

                // Don't try an stop the threads unless explicitly
                // configured to do so
                if (!clearReferencesStopThreads) {
                    continue;
                }

                // If the thread has been started via an executor, try
                // shutting down the executor
                try {
                    Field targetField = thread.getClass().getDeclaredField("target");
                    targetField.setAccessible(true);
                    Object target = targetField.get(thread);

                    if (target != null && target.getClass().getCanonicalName()
                            .equals("java.util.concurrent.ThreadPoolExecutor.Worker")) {
                        Field executorField = target.getClass().getDeclaredField("this$0");
                        executorField.setAccessible(true);
                        Object executor = executorField.get(target);
                        if (executor instanceof ThreadPoolExecutor) {
                            ((ThreadPoolExecutor) executor).shutdownNow();
                        }
                    }
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to terminate thread named [" + thread.getName() + "]", e);
                }

                // This method is deprecated and for good reason. This is
                // very risky code but is the only option at this point.
                // A *very* good reason for apps to do this clean-up
                // themselves.
                thread.stop();
            }
        }
    }
}

From source file:net.sf.ehcache.CacheManagerTest.java

/**
 * I have suggested that people can rely on the thread names to change priorities etc.
 * The names should stay fixed./*from   w w w. j a v a  2  s .  com*/
 */
public void testThreadNamingAndManipulation() {

    singletonManager = CacheManager.create();

    List threads = JVMUtil.enumerateThreads();

    for (int i = 0; i < threads.size(); i++) {
        Thread thread = (Thread) threads.get(i);
        String name = thread.getName();
        LOG.info(name);
    }
}