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:kr.co.aim.nanoframe.nanoFrameServiceProxy.java

/**
 * bundleContext:bundle/*  www .  j  av  a  2 s.  co  m*/
 * @return
 */
public static BundleContext getBundleContext() {
    if (bundleContext == null) {
        Thread thread = Thread.currentThread();
        log.info("GETBUNDLE : " + thread.getName());
        threadMap.put(thread.getId(), thread);

        try {
            Thread.sleep(BundleUtil.getServiceLookupTimeout());
        } catch (InterruptedException ex) {
            return bundleContext;
        } finally {
            threadMap.remove(thread.getId());
        }

        throw new nanoFrameErrorSignal(ErrorSignal.NotActive, "nanoframe.kernel is not Active.");
    } else
        return bundleContext;
}

From source file:com.buaa.cfs.utils.ShutdownThreadsHelper.java

/**
 * @param thread {@link Thread to be shutdown}
 * @param timeoutInMilliSeconds time to wait for thread to join after being
 *                              interrupted
 * @return <tt>true</tt> if the thread is successfully interrupted,
 * <tt>false</tt> otherwise/*ww  w.j a va 2 s. c o m*/
 * @throws InterruptedException
 */
public static boolean shutdownThread(Thread thread, long timeoutInMilliSeconds) {
    if (thread == null) {
        return true;
    }

    try {
        thread.interrupt();
        thread.join(timeoutInMilliSeconds);
        return true;
    } catch (InterruptedException ie) {
        LOG.warn("Interrupted while shutting down thread - " + thread.getName());
        return false;
    }
}

From source file:de.dal33t.powerfolder.PowerFolder.java

/**
 * Starts a PowerFolder controller with the given command line arguments
 *
 * @param args/* ww w  .j  a  v a  2 s .c o m*/
 */
public static void startPowerFolder(String[] args) {

    // Touch Logger immediately to initialize handlers.
    LoggingManager.isLogToFile();

    // Default exception logger
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e);
        }
    });

    CommandLine commandLine = parseCommandLine(args);
    if (commandLine == null) {
        return;
    }

    // -l --log console log levels (severe, warning, info, fine and finer).
    if (commandLine.hasOption("l")) {
        String levelName = commandLine.getOptionValue("l");
        Level level = LoggingManager.levelForName(levelName);
        if (level != null) {
            LoggingManager.setConsoleLogging(level);
        }
    }

    if (commandLine.hasOption("s")) {
        // Server mode, suppress debug output on console
        // Logger.addExcludeConsoleLogLevel(Logger.DEBUG);
    }

    if (commandLine.hasOption("h")) {
        // Show help
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS);
        return;
    }

    int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue());
    String portStr = commandLine.getOptionValue("k");
    if (StringUtils.isNotBlank(portStr)) {
        try {
            rconPort = Integer.valueOf(portStr.trim());
        } catch (Exception e) {
            log.warning("Unable to parse rcon port: " + portStr + ". " + e);
        }
    }

    boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort);

    if (commandLine.hasOption("k")) {
        if (runningInstanceFound) {
            System.out.println("Stopping " + NAME);
            // Send quit command
            RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT);
        } else {
            System.err.println("Process not running");
        }

        // stop
        return;
    }

    // set language from commandline to preferences
    if (commandLine.hasOption("g")) {
        Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g"));
    }

    if (JavaVersion.systemVersion().isOpenJDK()) {
        Object[] options = { "Open Oracle home page and exit", "Exit" };

        int n = JOptionPane.showOptionDialog(null,
                "You are using OpenJDK which is unsupported.\n"
                        + "Please install the client with bundled JRE or install the Oracle JRE",
                "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);

        if (n == 0) {
            try {
                BrowserLauncher.openURL("http://www.java.com");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return;
    }

    // The controller.
    Controller controller = Controller.createController();

    String[] files = commandLine.getArgs();
    // Parsing of command line completed

    boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e")
            || commandLine.hasOption("r") || commandLine.hasOption("a");
    // Try to start controller
    boolean startController = !commandContainsRemoteCommands || !runningInstanceFound;
    try {
        log.info("PowerFolder v" + Controller.PROGRAM_VERSION);

        // Start controller
        if (startController) {
            controller.startConfig(commandLine);
        }

        // Send remote command if there a files in commandline
        if (files != null && files.length > 0) {
            // Parse filenames and build remote command
            StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN);

            for (String file : files) {
                openFilesRCommand.append(file);
                // FIXME: Add ; separator ?
            }

            // Send remote command to running PowerFolder instance
            RemoteCommandManager.sendCommand(openFilesRCommand.toString());
        }

        if (commandLine.hasOption("e")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e"));
        }
        if (commandLine.hasOption("r")) {
            RemoteCommandManager
                    .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r"));
        }
        if (commandLine.hasOption("a")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a"));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.log(Level.SEVERE, "Throwable", t);
        return;
    }

    // Begin monitoring memory usage.
    if (controller.isStarted() && controller.isUIEnabled()) {
        ScheduledExecutorService service = controller.getThreadPool();
        service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES);
    }

    // Not go into console mode if ui is open
    if (!startController) {
        if (runningInstanceFound) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI);
        }
        return;
    }

    System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------");

    boolean restartRequested = false;
    do {
        // Go into restart loop
        while (controller.isStarted() || controller.isShuttingDown()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.log(Level.WARNING, "InterruptedException", e);
                return;
            }
        }

        restartRequested = controller.isRestartRequested();
        if (restartRequested) {
            Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
            for (Thread thread : threads.keySet()) {
                if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector")
                        || thread.getName().startsWith("ConHandler")) {
                    thread.interrupt();
                }
            }
            log.info("Restarting controller");
            System.out.println(
                    "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------");
            controller = null;
            System.gc();
            controller = Controller.createController();
            // Start controller
            controller.startConfig(commandLine);
        }
    } while (restartRequested);
}

From source file:com.ery.estorm.util.Threads.java

/**
 * Shutdown passed thread using isAlive and join.
 * //from  w  w  w .ja  v  a2 s  .co  m
 * @param joinwait
 *            Pass 0 if we're to wait forever.
 * @param t
 *            Thread to shutdown
 */
public static void shutdown(final Thread t, final long joinwait) {
    if (t == null)
        return;
    while (t.isAlive()) {
        try {
            t.join(joinwait);
        } catch (InterruptedException e) {
            LOG.warn(t.getName() + "; joinwait=" + joinwait, e);
        }
    }
}

From source file:es.darkhogg.hazelnutt.Hazelnutt.java

/**
 * Terminates the application in at most <i>time</i> milliseconds for
 * every alive thread. //from  w  w w.  j  a v a  2 s.c om
 * 
 * @param time Number of milliseconds to wait for each thread to terminate
 */
public static void terminate(long time) {
    Logger logger = getLogger();
    logger.info("Terminating application...");

    try {
        getFrame().dispose();

        // Get the root thread group
        ThreadGroup rootThreadGroup = Thread.currentThread().getThreadGroup();
        while (rootThreadGroup.getParent() != null) {
            rootThreadGroup = rootThreadGroup.getParent();
        }

        // Declare some collections
        Queue<ThreadGroup> threadGroups = new LinkedList<ThreadGroup>();
        Queue<Thread> threads = new LinkedList<Thread>();

        // Get ALL groups
        threadGroups.add(rootThreadGroup);
        while (!threadGroups.isEmpty()) {
            ThreadGroup group = threadGroups.remove();

            Thread[] subThreads = new Thread[group.activeCount() * 2];
            //group.enumerate( subThreads );
            for (Thread subThread : subThreads) {
                if (subThread != null) {
                    threads.add(subThread);
                }
            }

            ThreadGroup[] subThreadGroups = new ThreadGroup[group.activeGroupCount() * 2];
            for (ThreadGroup subThreadGroup : subThreadGroups) {
                if (subThreadGroup != null) {
                    threadGroups.add(subThreadGroup);
                }
            }
        }

        // Join a maximum of time milliseconds for all non-daemon threads
        while (!threads.isEmpty()) {
            Thread thread = threads.remove();
            LOGGER.trace(thread);

            if (!thread.isDaemon() && thread != Thread.currentThread()) {
                logger.trace("Waiting for thread '" + thread.getName() + "'");
                thread.join(time);
                if (thread.isAlive()) {
                    logger.trace("Interrupting thread '" + thread.getName() + "'");
                    thread.interrupt();
                }
            }
        }

    } catch (Throwable e) {
        LOGGER.warn("Interrupted while terminating application", e);

    } finally {
        // Exit the program
        System.exit(0);
    }
}

From source file:org.eclipse.jubula.rc.swing.listener.ComponentHandler.java

/**
 * Pretty prints the stack traces of all currently running threads to the 
 * log./*from  w  w  w  .j a  va2  s  . c  om*/
 */
private static void logStacktrace() {
    if (TRACE_COMPONENT_NOT_FOUND) {
        StringBuilder builder = new StringBuilder();
        builder.append("Logging stacktrace:" + SystemUtils.LINE_SEPARATOR); //$NON-NLS-1$
        Thread currentThread = Thread.currentThread();
        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
        for (Entry<Thread, StackTraceElement[]> stackTrace : stackTraces.entrySet()) {

            Thread thread = stackTrace.getKey();

            if (thread == currentThread) {
                builder.append("[current-thread] - "); //$NON-NLS-1$
            }

            builder.append(thread.getName() + ":" + SystemUtils.LINE_SEPARATOR); //$NON-NLS-1$
            for (StackTraceElement e : stackTrace.getValue()) {
                builder.append("\t" + e + SystemUtils.LINE_SEPARATOR); //$NON-NLS-1$
            }

        }

        builder.append(SystemUtils.LINE_SEPARATOR);
        log.warn(builder);
    }
}

From source file:org.objectweb.proactive.extensions.timitspmd.TimIt.java

@SuppressWarnings("deprecation")
public static void threadsCleaning() {
    ThreadGroup tg = Thread.currentThread().getThreadGroup().getParent();
    Thread[] threads = new Thread[200];
    int len = tg.enumerate(threads, true);
    int nbKilled = 0;

    for (int i = 0; i < len; i++) {
        Thread ct = threads[i];

        if ((ct.getName().indexOf("RMI RenewClean") >= 0) || (ct.getName().indexOf("ThreadInThePool") >= 0)) {
            nbKilled++;//  w w w .j  a  va 2  s .  c  o  m
            ct.stop();
        }
    }

    System.err.println(nbKilled + " thread(s) stopped on " + len);
}

From source file:uk.ac.horizon.ug.exploding.client.logging.LoggingUtils.java

/** init */
public static synchronized void init(Context context) {
    String packageName = context.getApplicationInfo().packageName;
    if (applicationDirName != null) {
        if (applicationDirName.equals(packageName))
            // no-op
            return;
        // close and re-initialise?
        Log.w(TAG, "Re-initialise logging with different package name: " + packageName + " vs "
                + applicationDirName);// w  ww  .ja  v a 2 s .  co m
        // TODO Log
        return;
    }
    applicationDirName = packageName;
    String fileName = "log_" + System.currentTimeMillis() + ".json";
    File dir = new File(LOG_ROOT_DIR, applicationDirName);
    if (dir.mkdir())
        Log.i(TAG, "Created log directory " + dir);
    if (!dir.exists()) {
        Log.e(TAG, "Log directory does not exist: " + dir + " - cannot log");
        return;
    }
    if (!dir.isDirectory()) {
        Log.e(TAG, "Log directory is not a directory: " + dir + " - cannot log");
        return;
    }
    File file = new File(LOG_ROOT_DIR + applicationDirName, fileName);
    if (file.exists())
        Log.w(TAG, "Appending to existing log: " + file);
    try {
        logWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file, true), Charset.forName("UTF-8")));
        Log.i(TAG, "Logging to " + file);
        logFile = file;
    } catch (Exception e) {
        Log.e(TAG, "Opening log file " + file + " - cannot log", e);
        logWriter = null;
    }
    logHeader(context);

    // dump exceptions!
    final UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            // TODO Auto-generated method stub
            try {
                JSONStringer js = new JSONStringer();
                js.object();
                js.key("thread");
                js.value(thread.getName());
                js.key("exception");
                js.value(ex.toString());
                js.key("stackTrace");
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                ex.printStackTrace(pw);
                js.value(sw.getBuffer().toString());
                js.endObject();
                log(LOGTYPE_UNCAUGHT_EXCEPTION, js.toString());
            } catch (Exception e) {
                Log.e(TAG, "Logging uncaught exception", e);
            }
            // cascade
            if (handler != null)
                handler.uncaughtException(thread, ex);
        }
    });
}

From source file:majordodo.task.BrokerTestUtils.java

public static String getThreadName(long threadid) {
    for (Thread t : Thread.getAllStackTraces().keySet()) {
        if (t.getId() == threadid) {
            return t.getName();
        }/*from   w w  w  .  j a  v  a2  s  .  c  om*/
    }
    return null;
}

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

private static void setExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override// w w w.  j a va  2 s .  c o  m
        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;
                MedSavantExceptionHandler.handleSessionExpiredException(see);
                return;
            }

            if (e instanceof LockException) {
                DialogUtils.displayMessage("Cannot modify database",
                        "<html>Another process is making changes.<br/>Please try again later.</html>");
                return;
            }

            e.printStackTrace();
            DialogUtils.displayException("Error", e.getLocalizedMessage(), e);
        }
    });
}