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:org.hyperic.hq.measurement.agent.server.MeasurementCommandsServer.java

private void interruptThread(Thread t) throws InterruptedException {
    if (t.isAlive()) {
        t.interrupt();// w w  w . j a  v a 2  s . c  o  m
        t.join(THREAD_JOIN_WAIT);

        if (t.isAlive()) {
            this.log.warn(t.getName() + " did not die within the " + "timeout period.  Killing it");
            t.stop();
        }
    }
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Deprecated
public void threadCleanup(File f) {
    while (!deleteFolder(f, false, 0, 0)) {
        l.error("Trying to stop more threads, list:");
        //List remaining threads
        ThreadGroup tg2 = Thread.currentThread().getThreadGroup();
        while (tg2.getParent() != null) {
            tg2 = tg2.getParent();/* w  w w.  java2s. c  o  m*/
        }
        //Object o = new Object();
        //o.notifyAll();
        Thread[] threads = new Thread[tg2.activeCount() + 1024];
        tg2.enumerate(threads, true);
        //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
        for (int i = 0; i < threads.length; i++) {
            Thread th = threads[i];
            if (th != null) {
                l.trace("Have thread: " + i + " : " + th.getName());
                if (th != null && th != Thread.currentThread()
                        && (AEThread2.isOurThread(th) || isAzThread(th))) {
                    l.trace("Suspending " + th.getName());
                    try {
                        th.suspend();
                        l.trace("ok");
                    } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                    }

                }
            }
        }
        for (int i = 0; i < threads.length; i++) {
            Thread th = threads[i];
            if (th != null) {
                l.trace("Have thread: " + i + " : " + th.getName());
                if (th != null && th != Thread.currentThread()
                        && (AEThread2.isOurThread(th) || isAzThread(th))) {
                    l.trace("Stopping " + th.getName());
                    try {
                        th.stop();
                        l.trace("ok");
                    } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                    }

                }
            }
        }
    }
    System.gc();
}

From source file:com.xpn.xwiki.monitor.api.MonitorPlugin.java

public void endRequest() {
    if (isActive() == false)
        return;/*w  w  w .  j  a v a  2  s .  com*/

    try {
        Thread cthread = Thread.currentThread();
        MonitorData mdata = (MonitorData) activeTimerDataList.get(cthread);
        if (mdata == null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("MONITOR: Thread " + cthread.getName() + " did not call startRequest");
            }
            return;
        }
        mdata.endRequest(true);
        addDuration(mdata.getDuration());
        addTimerDuration(mdata);
        removeFromActiveTimerDataList(cthread);
        addToTimerDataList(mdata);
    } catch (Throwable e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("MONITOR: endRequest failed with exception " + e);
            e.printStackTrace();
        }
    }
}

From source file:org.killbill.notificationq.NotificationQueueDispatcher.java

NotificationQueueDispatcher(final Clock clock, final NotificationQueueConfig config, final IDBI dbi,
        final MetricRegistry metricRegistry) {
    super("NotificationQ", Executors.newFixedThreadPool(config.getNbThreads() + 1, new ThreadFactory() {
        @Override/*ww  w  . j  a va 2 s  .  c o m*/
        public Thread newThread(final Runnable r) {
            final Thread th = new Thread(r);
            th.setName(config.getTableName() + "-th");
            th.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(final Thread t, final Throwable e) {
                    log.error("Uncaught exception for thread " + t.getName(), e);
                }
            });
            return th;
        }
    }), 1, config);

    this.clock = clock;
    this.config = config;
    this.nbProcessedEvents = new AtomicLong();
    final NotificationSqlDao sqlDao = dbi.onDemand(NotificationSqlDao.class);
    this.dao = new DBBackedQueue<NotificationEventModelDao>(clock, sqlDao, config,
            "notif-" + config.getTableName(), metricRegistry, null);

    this.queues = new TreeMap<String, NotificationQueue>();

    this.processedNotificationsSinceStart = metricRegistry.counter(
            MetricRegistry.name(NotificationQueueDispatcher.class, "processed-notifications-since-start"));
    this.perQueueProcessingTime = new HashMap<String, Histogram>();
    this.pendingNotificationsQ = new LinkedBlockingQueue<NotificationEventModelDao>(config.getQueueCapacity());

    this.metricRegistry = metricRegistry;
    this.pendingNotifications = metricRegistry.register(
            MetricRegistry.name(NotificationQueueDispatcher.class, "pending-notifications"),
            new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return pendingNotificationsQ.size();
                }
            });

    this.runners = new NotificationRunner[config.getNbThreads()];
    for (int i = 0; i < config.getNbThreads(); i++) {
        runners[i] = new NotificationRunner(pendingNotificationsQ, clock, config, objectMapper,
                nbProcessedEvents, queues, dao, perQueueProcessingTime, metricRegistry,
                processedNotificationsSinceStart);
    }
}

From source file:se.lth.cs.nlp.mediawiki.parser.MultistreamBzip2XmlDumpParser.java

@Override
public void run() {
    final AtomicBoolean terminate = new AtomicBoolean(false);
    final Logger logger = LoggerFactory.getLogger(MultistreamBzip2XmlDumpParser.class);
    //1. Start all worker threads
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new Worker();
        workers[i].setName("Dump Worker " + i);
    }/*w ww.j  a v a 2s .c om*/

    //Add an uncaught exception handler and allow for a graceful shutdown.
    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            logger.error("Fatal error in thread {}, terminating...", th.getName(), ex);
            for (Worker worker : workers) {
                worker.interrupt();
            }
            terminate.set(true);
        }
    };

    for (Worker worker : workers) {
        worker.setUncaughtExceptionHandler(h);
        worker.start();
    }

    //2. Seed them with data until there is no more
    byte[] data;
    while ((data = pageReader.next()) != null && !terminate.get()) {
        try {
            blocks.put(new PageBlock(data));
        } catch (InterruptedException e) {
            logger.error("Data put interrupted", e);
            break;
        }
    }

    for (int i = 0; i < workers.length; i++) {
        try {
            blocks.put(new PageBlock(null));
        } catch (InterruptedException e) {
            logger.info("Termination interrupted", e);
            break;
        }
    }

    //3. Await termination of all workers
    for (Worker worker : workers) {
        try {
            worker.join();
        } catch (InterruptedException e) {
            logger.error("Worker {} thread interrupted.", worker.getName(), e);
        }
    }

    output(Collections.<Page>emptyList());
}

From source file:com.garyclayburg.attributes.AttributeService.java

public void setScriptRunner(ScriptRunner runner) {
    log.info("setting scriptrunner...");
    this.runner = runner;
    if (runner.getRoots() != null) {
        initiallyScanned = false;//from w  ww .ja  v a  2  s . c o  m
        Runnable runnable = new Runnable() {
            public void run() {
                /*
                loading scripts in a background thread improves startup performance, especially when scripts
                are located on a slow file system such as S3
                 */
                synchronized (groovyClassMap) {
                    initiallyScanned = true;
                    scanGroovyClasses();
                }
            }
        };
        Thread t = new Thread(runnable);
        t.setName("pre-load" + String.valueOf(Math.random()).substring(2, 6));
        log.info("starting pre-load thread: " + t.getName());
        t.start();
    } else { // use read-only embedded scripts
        log.warn(
                "Custom groovy policy scripts not found.  Defaulting to read-only embedded groovy policy scripts");
        initiallyScanned = true;
        ClassLoader parent = getClass().getClassLoader();
        String scriptName = "embeddedgroovy/com/embedded/DefaultAttributes.groovy";
        InputStream groovyIS = parent.getResourceAsStream(scriptName);
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new BufferedReader(
                new InputStreamReader(groovyIS, Charset.forName(StandardCharsets.UTF_8.name())))) {
            int c;
            while ((c = reader.read()) != -1) {
                sb.append((char) c);
            }
            //                log.debug("complete default embedded groovy class:\n{}",sb.toString());
            GroovyClassLoader loader = new GroovyClassLoader(parent);
            Class parsedDefaultClass = loader.parseClass(sb.toString(), scriptName);
            groovyClassMap.clear();
            groovyClassMap.put(scriptName, parsedDefaultClass);
        } catch (IOException e) {
            log.warn("could not load embedded groovy scripts", e);
        }
        log.debug("finished reading embedded groovy");
    }
}

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

private static void clearReferencesStopTimerThread(Thread thread) {

    // Need to get references to:
    // - newTasksMayBeScheduled field
    // - queue field
    // - queue.clear()

    try {//from  ww  w. j a v a 2 s . c o m
        Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled");
        newTasksMayBeScheduledField.setAccessible(true);
        Field queueField = thread.getClass().getDeclaredField("queue");
        queueField.setAccessible(true);

        Object queue = queueField.get(thread);

        Method clearMethod = queue.getClass().getDeclaredMethod("clear");
        clearMethod.setAccessible(true);

        synchronized (queue) {
            newTasksMayBeScheduledField.setBoolean(thread, false);
            clearMethod.invoke(queue);
            queue.notify(); // In case queue was already empty.
        }

        if (logger.isLoggable(Level.FINE))
            logger.fine("A web application appears to have started a TimerThread named [" + thread.getName()
                    + "] via the java.util.Timer API but has failed to stop it. To prevent a memory leak, the timer (and hence the associated thread) has been forcibly cancelled.");

    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to terminate TimerThread named [" + thread.getName() + "]", e);
    }
}

From source file:com.hubcap.task.helpers.DefaultSearchHelper.java

@Override
public void run() {

    if (taskModel == null) {
        if (this.listener != null) {
            this.listener.processTaskHelperError(
                    new Exception("No Task Model Provided to DefaultSearchHelper, cannot run!"), false);
        }/*from  w  w w .  j a  v a2  s  .com*/
        die();
        return;
    }

    CommandLine cmd = taskModel.getCommandLine();

    int cLen = cmd.getArgs().length;
    // default search arguments are in the format
    // orgname (String) count (int)

    if (cLen < 1) {
        if (this.listener != null) {
            this.listener.processTaskHelperError(
                    new Exception("Default Search requires 1 argument, Organization (optional) Count"), false);
        }
        die();
    }

    if (cLen % 2 == 0) {

        // each helper has its own HttpClient
        ProcessModel.instance().updateRateLimitData();

        for (int i = 0; i < cLen; i += 2) {

            String orgName = cmd.getArgs()[i];
            int count = 10;

            try {
                count = Integer.parseInt(cmd.getArgs()[i + 1]);
            } catch (NumberFormatException ex) {
                ErrorUtils.printStackTrace(ex);
            }

            final long remainingRate = ProcessModel.instance().getRateLimitData().rate.remaining;
            final long maxResults = opts.containsKey("maxResults")
                    ? Integer.parseInt((String) opts.get("maxResults"))
                    : (remainingRate - 1);
            int maxPages = 100;
            if (remainingRate >= maxResults) {

                // pound that API until we get what we want!!

                // breaks out of the loop after
                // max pages
                searchHelperId.incrementAndGet();

                if (searchHelperId.get() > maxPages) {
                    break;
                }

                try {
                    synchronized (droneThreads) {

                        Thread t = new Thread(
                                new GitHubOrgScavengerDrone(sewingMachine, this.taskModel, orgName, count));
                        droneThreads.add(t);
                        t.setName("drone" + String.valueOf(owner.getTaskId()) + "-"
                                + String.valueOf(new Date().getTime()));
                        t.setDaemon(false);
                        t.start();
                    }
                } catch (RejectedExecutionException ex) {
                    ErrorUtils.printStackTrace(ex);
                    break;
                }

            } else {
                System.err.println("Your rate limit is exhausted, try again later!");
            }
        }
    }

    if (ProcessModel.instance().getVerbose()) {
        System.out.println("Waiting for Drone Threads: " + droneThreads.size());
    }

    // wait for all threads to complete
    while (droneThreads.size() > 0) {
        Iterator<Thread> it = droneThreads.iterator();
        while (it.hasNext()) {
            Thread currDroneThread = it.next();

            if (currDroneThread.getState() == State.TERMINATED) {

                if (ProcessModel.instance().getVerbose()) {
                    System.err.println("Removing Drone Thread: " + currDroneThread.getName());
                }

                it.remove();
            }
        }

        // sleep and do it again
        if (!ThreadUtils.safeSleep(
                Constants.NEW_THREAD_SPAWN_BREATHING_TIME
                        + Constants.NEW_THREAD_SPAWN_BREATHING_TIME * 1 / SewingMachine.MAX_THREADS_PER_MACHINE,
                ProcessModel.instance().getVerbose())) {
            System.err.println("INTERRUPTED WAIT FOR DRONE THREADS!");
            break;
        }
    }

    System.out.println("No More Drones!");
    // wait a tad

    synchronized (taskModel) {
        Map<String, Object> aggData = taskModel.getAggregateDataMap();

        if (aggData != null) {

            for (String key : aggData.keySet()) {

                Object value = aggData.get(key);

                if (value instanceof ScavengerModel == false) {
                    continue;
                }

                // ask the model to calculate from its current state
                ScavengerModel model = (ScavengerModel) value;
                synchronized (model) {
                    model.calculate();
                }
            }

            listener.processTaskHelperData(taskModel);
        }
    }
    die();
}

From source file:org.ocsoft.olivia.logger.LogStation.java

/**
 * ????.//from   w ww  .j  av a 2  s. c o  m
 */
private LogStation() {

    //??????????
    try {
        setUpLogFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //??
    for (Handler h : logger.getHandlers()) {
        if (h instanceof ConsoleHandler)
            logger.removeHandler(h);
    }
    //???????
    logger.setUseParentHandlers(false);
    //??
    this.ch = createConsoleLogHandler();
    logger.addHandler(ch);
    //?
    this.fh = createLogFileHandler();
    logger.addHandler(fh);
    //????????
    uch = new UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            OliviaLogger.fatal("UNCAUGHT_EXCEPTION", "uncaught exception occured", new LogData() {
                {
                    exception(ex);
                    put("thread", th.getName());
                }
            });
        }
    };
    Thread.currentThread().setUncaughtExceptionHandler(uch);
    //?
    logger.setLevel(Level.ALL);
}

From source file:org.apache.hadoop.hbase.catalog.TestCatalogTracker.java

private void startWaitAliveThenWaitItLives(final Thread t, final int ms) {
    t.start();//from  ww  w  .  ja v a2 s.  c o  m
    while (!t.isAlive()) {
        // Wait
    }
    // Wait one second.
    Threads.sleep(ms);
    Assert.assertTrue("Assert " + t.getName() + " still waiting", t.isAlive());
}