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:net.darkmist.clf.IndexedLogFileHandler.java

/** Checks for index file and presence of the user in the index if it exists.
 * @param file The log file being examined
 * @param base The base name of the log file
 * @return true if the index file exists and the index file does NOT contain the user.
 *//*from  www . j  ava  2  s  . c  o m*/
private boolean notInIndex(File file, String base) {
    File dir;
    File index;
    InputStream in = null;
    String previousThreadName;
    Thread thread;
    int bufSize;

    if ((dir = file.getParentFile()) == null) {
        logger.warn("Log file " + file + " doesn't have a parent directory?");
        return false;
    }
    index = new File(dir, base + INDEX_EXT);
    if (!index.exists()) {
        if (logger.isDebugEnabled())
            logger.debug("no index file " + index + " for log file " + file);
        return false;
    }
    thread = Thread.currentThread();
    previousThreadName = thread.getName();
    thread.setName("idx: " + index);
    if (logger.isDebugEnabled())
        logger.debug("index scan of " + index);
    bufSize = (int) Math.min(index.length(), MAX_BUF_SIZE);
    try {
        in = new GZIPInputStream(new BufferedInputStream(new FileInputStream(index), bufSize));
        if (LineMatcher.readerContains(usrPat, new BufferedReader(new InputStreamReader(in)))) {
            logger.debug("found usr in index");
            return false;
        }
        logger.debug("did not find usr in index");
        return true;
    } catch (IOException e) {
        logger.warn("IOException reading from index " + index, e);
    } finally {
        in = Util.close(in, logger, index.toString());
        thread.setName(previousThreadName);
    }
    return false;
}

From source file:com.yahoo.omid.tso.TSOHandler.java

public void start() {
    this.flushThread = new FlushThread();
    this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override/*w w w.  j a v a  2  s.  co  m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
            t.setDaemon(true);
            t.setName("Flush Thread");
            return t;
        }
    });
    this.flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
    this.executor = Executors.newSingleThreadExecutor();
}

From source file:com.apptentive.android.sdk.Apptentive.java

private synchronized static void asyncFetchConversationToken(final Context context) {
    Thread thread = new Thread() {
        @Override//from  w ww.  j ava  2 s  .c  o m
        public void run() {
            fetchConversationToken(context);
        }
    };
    Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            Log.w("Caught UncaughtException in thread \"%s\"", throwable, thread.getName());
            MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
        }
    };
    thread.setUncaughtExceptionHandler(handler);
    thread.setName("Apptentive-FetchConversationToken");
    thread.start();
}

From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java

@Override
public void onThreadCreated(WebSocket websocket, ThreadType threadType, Thread thread) throws Exception {
    String identifier = api.getIdentifierString();
    String guildId = guild.getId();
    switch (threadType) {
    case CONNECT_THREAD:
        thread.setName(identifier + " AudioWS-ConnectThread (guildId: " + guildId + ')');
        break;//w  w  w  .  ja v  a 2s . c o  m
    case FINISH_THREAD:
        thread.setName(identifier + " AudioWS-FinishThread (guildId: " + guildId + ')');
        break;
    case WRITING_THREAD:
        thread.setName(identifier + " AudioWS-WriteThread (guildId: " + guildId + ')');
        break;
    case READING_THREAD:
        thread.setName(identifier + " AudioWS-ReadThread (guildId: " + guildId + ')');
        break;
    default:
        thread.setName(identifier + " AudioWS-" + threadType + " (guildId: " + guildId + ')');
    }
}

From source file:com.spotify.ffwd.AgentCore.java

private Thread setupShutdownHook(final Injector primary, final CountDownLatch shutdown) {
    final Thread thread = new Thread() {
        @Override/* w ww.j  a va2s  . c om*/
        public void run() {
            try {
                AgentCore.this.stop(primary);
            } catch (Exception e) {
                log.error("AgentCore#stop(Injector) failed", e);
            }

            shutdown.countDown();
        }
    };

    thread.setName("ffwd-agent-core-shutdown-hook");

    return thread;
}

From source file:com.apptentive.android.sdk.Apptentive.java

private static void asyncFetchAppConfiguration(final Context context) {
    Thread thread = new Thread() {
        public void run() {
            fetchAppConfiguration(context, GlobalInfo.isAppDebuggable);
        }/*w  w  w  .  j  a va 2s .  c  o  m*/
    };
    Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            Log.e("Caught UncaughtException in thread \"%s\"", throwable, thread.getName());
            MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
        }
    };
    thread.setUncaughtExceptionHandler(handler);
    thread.setName("Apptentive-FetchAppConfiguration");
    thread.start();
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Submits stats logs to the server. Spawns a separate thread to do all the
 * work so that we don't block the UI if the server doesn't respond.
 *//*from w  ww  . j a v a2s  . c om*/
private void uploadLogs() {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            String oldLogSet = rotate();
            uploadLogs(oldLogSet);
        }
    };
    Thread t = new Thread(r);
    t.setName("SubmitLogs");
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:org.apache.kudu.client.MiniKuduCluster.java

/**
 * Starts a process using the provided command and configures it to be daemon,
 * redirects the stderr to stdout, and starts a thread that will read from the process' input
 * stream and redirect that to LOG.// w w  w .  j  av  a 2s . c om
 * @param port RPC port used to identify the process
 * @param command process and options
 * @return The started process
 * @throws Exception Exception if an error prevents us from starting the process,
 * or if we were able to start the process but noticed that it was then killed (in which case
 * we'll log the exit value).
 */
private Process configureAndStartProcess(int port, List<String> command) throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    if (miniKdc != null) {
        processBuilder.environment().putAll(miniKdc.getEnvVars());
    }
    Process proc = processBuilder.start();
    ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable(
            proc.getInputStream());
    Thread thread = new Thread(printer);
    thread.setDaemon(true);
    thread.setName(Iterables.getLast(Splitter.on(File.separatorChar).split(command.get(0))) + ":" + port);
    PROCESS_INPUT_PRINTERS.add(thread);
    thread.start();

    Thread.sleep(300);
    try {
        int ev = proc.exitValue();
        throw new Exception(String.format("We tried starting a process (%s) but it exited with value=%s",
                command.get(0), ev));
    } catch (IllegalThreadStateException ex) {
        // This means the process is still alive, it's like reverse psychology.
    }
    return proc;
}

From source file:org.jboss.bpm.report.JasperService.java

public void createAsync() {
    Thread t = new Thread(new Runnable() {
        public void run() {
            log.info("Creating Jasper service in the background");
            create();/*from  w w w.jav  a 2 s . c om*/
        }
    });

    t.setName("JasperService-Init");
    t.start();
}

From source file:edu.codemonkey.zendroid.MainActivity.java

@Override
protected void onResume() {
    super.onResume();

    handler = new Handler() {

        @Override//from w  ww . ja  va  2 s.  c o m
        public void handleMessage(Message msg) {
            // TODO what happens if a thread is running when the handler is resumed?
            ZenError.log("Handler received: " + msg.what + " Object: " + msg.obj);

            if (msg.obj != null && !(msg.obj instanceof String)) {
                ZenError.log(
                        "Warning: handler received unexpected non-null Message.obj not instanceof String.");
            }
            if (msg.what != Constants.POST_TOAST && msg.obj instanceof String
                    && !((String) msg.obj).startsWith(Constants.threadID + "")) {

                Utilities.removeFile(msg.obj.toString().split(" ", 1)[0]);
                return;
            }

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(totalCommand.getWindowToken(), 0);
            switch (msg.what) {
            case Constants.INSTALL_COMPLETE:
                // TODO do nothing, no output to show user.
                break;
            case Constants.INSTALL_ERROR:
                // TODO show error to user.
                break;
            case Constants.PROGRESS_DIALOG_START:
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage(msg.obj.toString());
                progressDialog.setCancelable(false);
                progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (scanThread != null && scanThread.isAlive()) {
                                    scanThread = null;
                                    Constants.threadID = 0;
                                }
                                progressDialog.dismiss();
                                btnStart.setEnabled(true);
                            }
                        });
                progressDialog.show();
                break;
            case Constants.PROGRESS_DIALOG_DISMISS:
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    btnStart.setEnabled(true);
                }
                break;
            case Constants.PROGRESS_DIALOG_CHANGE_TEXT:
                if (progressDialog.isShowing())
                    progressDialog.setMessage((String) msg.obj);
                else
                    ZenError.log("Progress dialog is not showing but text changed.");
                break;
            case Constants.SCAN_ERROR_NULL_PROCESS:
                txtResults.setText("Unable to start compiled Nmap program.");
                btnStart.setEnabled(true);
                break;
            case Constants.SCAN_ERROR_IOEXCEPTION:
                StringBuilder sb = new StringBuilder("An I/O error occured.\n");
                sb.append(msg.obj);
                sb.append('\n');
                if (forceRoot) {
                    sb.append("Force Root is turned on - are you sure the \"su\" command is available?");
                }
                AlertDialog.Builder alertIOException = new AlertDialog.Builder(MainActivity.this)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertIOException.setMessage(sb);
                alertIOException.show();
                txtResults.setText((String) msg.obj);
                btnStart.setEnabled(true);
                break;
            case Constants.SCAN_ERROR_STANDARD_ERROR:
                AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this).setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alert.setMessage((String) msg.obj);
                alert.show();
                btnStart.setEnabled(true);
                break;
            case Constants.SCAN_COMPLETE:
                String result = (String) msg.obj;
                txtResults.setText(result);
                CurrentSelections.getInstance().getCurrentScanObject()
                        .setFullCommand(totalCommand.getText().toString());
                CurrentSelections.getInstance().getCurrentScanObject().setResult("" + Constants.threadID);
                break;
            default:
                Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                ZenError.log("Handler received unexpected message that the switch statement does not allow.");
            }
        }
    };

    //      SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    //      autoCompleteTarget.setText(settings.getString("target", ""));
    //      etxtArguments.setText(settings.getString("args", ""));
    //      forceRoot = settings.getBoolean("forceRoot", false);
    //      int lastVersionRun = settings.getInt("versionLastRun", -1);
    //      showLogcat = settings.getBoolean("showLogcat", false);
    //      ZenError.setLogcatVisible(showLogcat);

    if (LocalDBHandler.VERSIONUPDATED) {
        LocalDBHandler.VERSIONUPDATED = false;
        hasRoot = forceRoot ? forceRoot : Utilities.canGetRoot();
        Constants.threadID = System.currentTimeMillis();
        Install install = new Install(MainActivity.context,
                Utilities.getApplicationFolder(MainActivity.context, "bin"), hasRoot, Constants.threadID);
        Thread installThread = new Thread(install);
        installThread.setName("Install Thread");
        installThread.start();
    }

    if (forceRoot) {
        ZenError.log("Found true forceRoot key in Shared Preferences.");
        hasRoot = true;
    }

}