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:io.seldon.importer.articles.GeneralItemAttributesImporter.java

/**
* @param args/*from ww w .  j a  va2s . com*/
* @throws InterruptedException 
* @throws FileNotFoundException 
*/
public static void main(String[] args) throws InterruptedException, FileNotFoundException {

    FailFast failFast = new FailFast(Thread.currentThread());
    { // Fail Fast thread
        Thread fail_fast_thread = new Thread(failFast);
        fail_fast_thread.setName("fail_fast_thread");
        fail_fast_thread.start();
    }

    try {
        Args.parse(GeneralItemAttributesImporter.class, args);

        UrlFetcher urlFetcher = null;
        { // setup the correct UrlFetcher
            if (jsSupport) {
                urlFetcher = new JsSupporedUrlFetcher(httpGetTimeout);
            } else {
                urlFetcher = new SimpleUrlFetcher(httpGetTimeout);
            }
        }

        { // Determine opMode by checking for urlFile
            if (urlFile != null) {
                opMode = OperationMode.OPERATION_MODE_FILE_IMPORTER;
            }
        }
        { // setup the attribute_detail_list
            attribute_detail_list = getAttributeDetailList(attributesConfigFile);
        }
        if (testUrl != null) {
            test_url_and_exit(urlFetcher, testUrl);
        }

        DefaultApiClient client = new DefaultApiClient(apiUrl, consumerKey, consumerSecret, API_TIMEOUT);

        GeneralItemAttributesImporter fixer = new GeneralItemAttributesImporter(client);

        fixer.setFailFast(failFast);
        fixer.run(urlFetcher);

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        Args.usage(GeneralItemAttributesImporter.class);
    } catch (Exception e) {
        e.printStackTrace();
        Args.usage(GeneralItemAttributesImporter.class);
    }
}

From source file:com.cic.datacrawl.ui.Main.java

/**
 * Main entry point. Creates a debugger attached to a Rhino
 * {@link com.cic.datacrawl.ui.shell.Shell} shell session.
 *///from   w  ww .  j  a v  a 2s  .  c  o  m
public static void main(final String[] args) {
    if (System.getProperties().get("os.name").toString().toLowerCase().indexOf("linux") >= 0)
        System.setProperty("sun.awt.xembedserver", "true");
    try {
        String path = null;
        boolean reflash = true;
        if (args != null && args.length > 0) {
            if (args[0].equalsIgnoreCase("-h")) {
                System.out.println("Command Format: \n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar "
                        + "[-d config path]\n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar "
                        + "[-d config path_1;path_2;....;path_n]\n");
            }

            int pathIndex = ArrayUtils.indexOf(args, "-d");
            if (pathIndex >= 0) {
                try {
                    path = args[pathIndex + 1];
                    File f = new File(path);
                    if (!f.exists()) {
                        LOG.warn("Invalid path of configuration. " + "Using default configuration.");
                    }
                } catch (Throwable e) {
                    LOG.warn("Invalid path of configuration. " + "Using default configuration.");
                }
            }
            // int reflashIndex = ArrayUtils.indexOf(args, "-r");
            //
            // reflash = new Boolean(args[reflashIndex + 1]).booleanValue();
        }
        if (path == null || path.trim().length() == 0)
            path = Config.INSTALL_PATH + File.separator + "config" + File.separator + "beans";

        LOG.debug("Config Path: \"" + path + "\"");
        // ?IOC
        // ????
        // ?
        ApplicationContext.initialiaze(path, reflash);
        System.setProperty(ApplicationContext.CONFIG_PATH, path);
        // js???
        InitializerRegister.getInstance().execute();
        // ???
        //VerifyCodeInputDialog.init();
        // ??
        //initTestData();
        // ?GUI
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                startupGUI(args);
            }
        });
        thread.setName("UI_Thread");
        thread.start();

    } catch (Throwable e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:org.apache.omid.examples.ParallelExecution.java

public static void main(String[] args) throws Exception {

    LOG.info("Parsing the command line arguments");
    int maxThreads = Runtime.getRuntime().availableProcessors();
    if (args != null && args.length > 2 && StringUtils.isNotEmpty(args[2])) {
        maxThreads = Integer.parseInt(args[2]);
    }/*from w  w  w. j a v a2  s.com*/
    LOG.info("Execute '{}' concurrent threads", maxThreads);

    for (int i = 0; i < maxThreads; i++) {
        final SnapshotIsolationExample example = new SnapshotIsolationExample(args);
        example.setRowIdGenerator(new RandomRowIdGenerator());
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                long lastHeartBeatTime = System.currentTimeMillis();
                long counter = 0;
                long errorCounter = 0;
                while (true) {
                    LOG.info("New cycle starts");
                    try {
                        example.execute();
                        counter++;
                    } catch (IOException | RollbackException | IllegalStateException e) {
                        LOG.error("", e);
                        errorCounter++;
                    }
                    if (System.currentTimeMillis() > lastHeartBeatTime + heartBeatInterval) {
                        LOG.error(String.format("%s cycles executed, %s errors", counter, errorCounter));
                        lastHeartBeatTime = System.currentTimeMillis();
                    }
                }
            }
        });
        t.setName(String.format("SnapshotIsolationExample thread %s/%s", i + 1, maxThreads));
        t.start();
    }

}

From source file:org.apache.hadoop.mapred.Child.java

public static void main(String[] args) throws Throwable {
    LOG.debug("Child starting");

    final JobConf defaultConf = new JobConf();
    String host = args[0];//from  w w  w.ja  v a  2 s .  com
    int port = Integer.parseInt(args[1]);
    final InetSocketAddress address = NetUtils.makeSocketAddr(host, port);
    final TaskAttemptID firstTaskid = TaskAttemptID.forName(args[2]);
    final String logLocation = args[3];
    final int SLEEP_LONGER_COUNT = 5;
    int jvmIdInt = Integer.parseInt(args[4]);
    JVMId jvmId = new JVMId(firstTaskid.getJobID(), firstTaskid.isMap(), jvmIdInt);
    String prefix = firstTaskid.isMap() ? "MapTask" : "ReduceTask";

    cwd = System.getenv().get(TaskRunner.HADOOP_WORK_DIR);
    if (cwd == null) {
        throw new IOException("Environment variable " + TaskRunner.HADOOP_WORK_DIR + " is not set");
    }

    // file name is passed thru env
    String jobTokenFile = System.getenv().get(UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION);
    Credentials credentials = TokenCache.loadTokens(jobTokenFile, defaultConf);
    LOG.debug("loading token. # keys =" + credentials.numberOfSecretKeys() + "; from file=" + jobTokenFile);

    Token<JobTokenIdentifier> jt = TokenCache.getJobToken(credentials);
    SecurityUtil.setTokenService(jt, address);
    UserGroupInformation current = UserGroupInformation.getCurrentUser();
    current.addToken(jt);

    UserGroupInformation taskOwner = UserGroupInformation.createRemoteUser(firstTaskid.getJobID().toString());
    taskOwner.addToken(jt);

    // Set the credentials
    defaultConf.setCredentials(credentials);

    final TaskUmbilicalProtocol umbilical = taskOwner
            .doAs(new PrivilegedExceptionAction<TaskUmbilicalProtocol>() {
                @Override
                public TaskUmbilicalProtocol run() throws Exception {
                    return (TaskUmbilicalProtocol) RPC.getProxy(TaskUmbilicalProtocol.class,
                            TaskUmbilicalProtocol.versionID, address, defaultConf);
                }
            });

    int numTasksToExecute = -1; //-1 signifies "no limit"
    int numTasksExecuted = 0;
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                if (taskid != null) {
                    TaskLog.syncLogs(logLocation, taskid, isCleanup, currentJobSegmented);
                }
            } catch (Throwable throwable) {
            }
        }
    });
    Thread t = new Thread() {
        public void run() {
            //every so often wake up and syncLogs so that we can track
            //logs of the currently running task
            while (true) {
                try {
                    Thread.sleep(5000);
                    if (taskid != null) {
                        TaskLog.syncLogs(logLocation, taskid, isCleanup, currentJobSegmented);
                    }
                } catch (InterruptedException ie) {
                } catch (IOException iee) {
                    LOG.error("Error in syncLogs: " + iee);
                    System.exit(-1);
                }
            }
        }
    };
    t.setName("Thread for syncLogs");
    t.setDaemon(true);
    t.start();

    String pid = "";
    if (!Shell.WINDOWS) {
        pid = System.getenv().get("JVM_PID");
    }
    JvmContext context = new JvmContext(jvmId, pid);
    int idleLoopCount = 0;
    Task task = null;

    UserGroupInformation childUGI = null;

    final JvmContext jvmContext = context;
    try {
        while (true) {
            taskid = null;
            currentJobSegmented = true;

            JvmTask myTask = umbilical.getTask(context);
            if (myTask.shouldDie()) {
                break;
            } else {
                if (myTask.getTask() == null) {
                    taskid = null;
                    currentJobSegmented = true;

                    if (++idleLoopCount >= SLEEP_LONGER_COUNT) {
                        //we sleep for a bigger interval when we don't receive
                        //tasks for a while
                        Thread.sleep(1500);
                    } else {
                        Thread.sleep(500);
                    }
                    continue;
                }
            }
            idleLoopCount = 0;
            task = myTask.getTask();
            task.setJvmContext(jvmContext);
            taskid = task.getTaskID();

            // Create the JobConf and determine if this job gets segmented task logs
            final JobConf job = new JobConf(task.getJobFile());
            currentJobSegmented = logIsSegmented(job);

            isCleanup = task.isTaskCleanupTask();
            // reset the statistics for the task
            FileSystem.clearStatistics();

            // Set credentials
            job.setCredentials(defaultConf.getCredentials());
            //forcefully turn off caching for localfs. All cached FileSystems
            //are closed during the JVM shutdown. We do certain
            //localfs operations in the shutdown hook, and we don't
            //want the localfs to be "closed"
            job.setBoolean("fs.file.impl.disable.cache", false);

            // set the jobTokenFile into task
            task.setJobTokenSecret(JobTokenSecretManager.createSecretKey(jt.getPassword()));

            // setup the child's mapred-local-dir. The child is now sandboxed and
            // can only see files down and under attemtdir only.
            TaskRunner.setupChildMapredLocalDirs(task, job);

            // setup the child's attempt directories
            localizeTask(task, job, logLocation);

            //setupWorkDir actually sets up the symlinks for the distributed
            //cache. After a task exits we wipe the workdir clean, and hence
            //the symlinks have to be rebuilt.
            TaskRunner.setupWorkDir(job, new File(cwd));

            //create the index file so that the log files 
            //are viewable immediately
            TaskLog.syncLogs(logLocation, taskid, isCleanup, logIsSegmented(job));

            numTasksToExecute = job.getNumTasksToExecutePerJvm();
            assert (numTasksToExecute != 0);

            task.setConf(job);

            // Initiate Java VM metrics
            initMetrics(prefix, jvmId.toString(), job.getSessionId());

            LOG.debug("Creating remote user to execute task: " + job.get("user.name"));
            childUGI = UserGroupInformation.createRemoteUser(job.get("user.name"));
            // Add tokens to new user so that it may execute its task correctly.
            for (Token<?> token : UserGroupInformation.getCurrentUser().getTokens()) {
                childUGI.addToken(token);
            }

            // Create a final reference to the task for the doAs block
            final Task taskFinal = task;
            childUGI.doAs(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    try {
                        // use job-specified working directory
                        FileSystem.get(job).setWorkingDirectory(job.getWorkingDirectory());
                        taskFinal.run(job, umbilical); // run the task
                    } finally {
                        TaskLog.syncLogs(logLocation, taskid, isCleanup, logIsSegmented(job));
                        TaskLogsTruncater trunc = new TaskLogsTruncater(defaultConf);
                        trunc.truncateLogs(new JVMInfo(
                                TaskLog.getAttemptDir(taskFinal.getTaskID(), taskFinal.isTaskCleanupTask()),
                                Arrays.asList(taskFinal)));
                    }

                    return null;
                }
            });
            if (numTasksToExecute > 0 && ++numTasksExecuted == numTasksToExecute) {
                break;
            }
        }
    } catch (FSError e) {
        LOG.fatal("FSError from child", e);
        umbilical.fsError(taskid, e.getMessage(), jvmContext);
    } catch (Exception exception) {
        LOG.warn("Error running child", exception);
        try {
            if (task != null) {
                // do cleanup for the task
                if (childUGI == null) {
                    task.taskCleanup(umbilical);
                } else {
                    final Task taskFinal = task;
                    childUGI.doAs(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            taskFinal.taskCleanup(umbilical);
                            return null;
                        }
                    });
                }
            }
        } catch (Exception e) {
            LOG.info("Error cleaning up", e);
        }
        // Report back any failures, for diagnostic purposes
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        exception.printStackTrace(new PrintStream(baos));
        if (taskid != null) {
            umbilical.reportDiagnosticInfo(taskid, baos.toString(), jvmContext);
        }
    } catch (Throwable throwable) {
        LOG.fatal("Error running child : " + StringUtils.stringifyException(throwable));
        if (taskid != null) {
            Throwable tCause = throwable.getCause();
            String cause = tCause == null ? throwable.getMessage() : StringUtils.stringifyException(tCause);
            umbilical.fatalError(taskid, cause, jvmContext);
        }
    } finally {
        RPC.stopProxy(umbilical);
        shutdownMetrics();
        // Shutting down log4j of the child-vm... 
        // This assumes that on return from Task.run() 
        // there is no more logging done.
        LogManager.shutdown();
    }
}

From source file:org.unitime.timetable.onlinesectioning.MultiLock.java

public static void main(String[] args) {
    try {//from  ww w.j av a2s  .  c o  m
        final MultiLock lock = new MultiLock();
        for (int i = 1; i <= 1000; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            int nrCourses = 2 + ToolBox.random(9);
                            Set<Long> courses = new HashSet<Long>();
                            String s = "";
                            for (int i = 0; i < nrCourses; i++) {
                                long courseId;
                                do {
                                    courseId = ToolBox.random(10000);
                                } while (!courses.add(courseId));
                                s += (i > 0 ? ", " : "") + courseId;
                            }
                            System.out.println(Thread.currentThread().getName() + "Locking: [" + s + "]");
                            Unlock l = lock.lock(courses);
                            System.out.println(Thread.currentThread().getName() + "Locked: [" + s + "]");
                            try {
                                Thread.sleep(ToolBox.random(1000));
                            } catch (InterruptedException e) {
                            }
                            System.out.println(Thread.currentThread().getName() + "Unlocking: [" + s + "]");
                            l.release();
                            System.out.println(Thread.currentThread().getName() + "Unlocked: [" + s + "]");
                        }
                    } catch (Exception e) {
                        System.err.println(Thread.currentThread().getName() + e.getMessage());
                        e.printStackTrace();
                    }
                }
            });
            t.setName("[T" + i + "]: ");
            t.start();
        }
        for (int i = 1; i <= 3; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            try {
                                Thread.sleep(ToolBox.random(5000));
                            } catch (InterruptedException e) {
                            }
                            System.out.println(Thread.currentThread().getName() + "Locking all...");
                            lock.lockAll();
                            System.out.println(Thread.currentThread().getName() + "All locked.");
                            try {
                                Thread.sleep(ToolBox.random(1000));
                            } catch (InterruptedException e) {
                            }
                            System.out.println(Thread.currentThread().getName() + "Unlocking all.");
                            lock.unlockAll();
                            System.out.println(Thread.currentThread().getName() + "All unlocked.");
                        }
                    } catch (Exception e) {
                        System.err.println(Thread.currentThread().getName() + e.getMessage());
                        e.printStackTrace();
                    }
                }
            });
            t.setName("[A" + i + "]: ");
            t.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static Thread newThread(String threadName, Runnable runnable) {

    Thread thread = new Thread(runnable);
    thread.setName(threadName);
    return thread;
}

From source file:Main.java

public static void run(Runnable runnable, String threadName, boolean daemon) {

    Thread thread = new Thread(runnable, threadName);

    thread.setName(threadName);

    thread.setDaemon(daemon);// w w w. ja v a 2 s . co m

    thread.start();
}

From source file:Main.java

public static ThreadFactory createSimpleThreadFactory(final String name) {
    return r -> {
        Thread t = new Thread(r);
        t.setName(name);
        t.setDaemon(true);/*from w  w  w .j  a  v a 2  s.co  m*/
        return t;
    };
}

From source file:Main.java

public static ThreadFactory createThreadFactory(final String prefix) {
    return new ThreadFactory() {
        private AtomicInteger size = new AtomicInteger();

        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(prefix + size.incrementAndGet());
            if (thread.isDaemon()) {
                thread.setDaemon(false);
            }//from   www . ja  v  a  2  s . c  om
            return thread;
        }
    };
}

From source file:Main.java

public static ThreadFactory newNamedThreadFactory(final String name) {
    return new ThreadFactory() {
        @Override// w  ww.  j  a v a 2 s  . co m
        public Thread newThread(final Runnable r) {
            Thread t = new Thread(r);
            t.setName(name);
            return t;
        }
    };
}