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:helma.util.Logger.java

/**
 * Append a message to the log./*w  w  w. j  av a  2  s  .c  o m*/
 * @param level a string representing the log level
 * @param msg the log message
 * @param exception an exception, or null
 */
protected void log(String level, Object msg, Throwable exception) {
    lastMessage = System.currentTimeMillis();
    // it's enough to render the date every second
    if ((lastMessage - 1000) > dateLastRendered) {
        renderDate();
    }
    // add a safety net so we don't grow indefinitely even if writer thread
    // has gone. the 2000 entries threshold is somewhat arbitrary. 
    if (entries.size() < 2000) {
        String message = msg == null ? "null" : msg.toString();
        Thread thread = Thread.currentThread();
        String threadId = "[" + thread.getName() + "] ";
        entries.add(new Entry(dateCache, level, message, threadId, exception));
    }
}

From source file:org.noroomattheinn.utils.ThreadManager.java

public synchronized void shutDown() {
    shuttingDown = true;/*from  w  ww . ja v  a  2s.  c o  m*/
    timer.cancel();
    for (Stoppable s : stopList) {
        s.stop();
    }

    int nActive;
    do {
        nActive = 0;
        logger.finest("Iterating through terminate loop");
        for (Thread t : threads) {
            Thread.State state = t.getState();
            switch (state) {
            case NEW:
            case RUNNABLE:
                nActive++;
                logger.finest("Active thread: " + t.getName());
                break;

            case TERMINATED:
                logger.finest("Terminated thread: " + t.getName());
                break;

            case BLOCKED:
            case TIMED_WAITING:
            case WAITING:
                logger.finest("About to interrupt thread: " + t.getName());
                nActive++;
                t.interrupt();
                Utils.yieldFor(100);
                break;

            default:
                break;
            }
        }
    } while (nActive > 0);
}

From source file:de.slub.elasticsearch.river.fedora.FedoraRiver.java

private void safeStart(Thread thread) {
    if (thread != null && thread.getState().equals(Thread.State.NEW)) {
        thread.start();/*  ww  w.jav a 2 s  .co m*/
        logger.info("Started thread: [{}] {}", thread.getId(), thread.getName());
    }
}

From source file:org.apache.rya.streams.client.command.AddQueryAndLoadStatementsStreamsIT.java

@Test
public void testLubm() throws Exception {
    // Arguments that add a query to Rya Streams.
    final String query = "PREFIX lubm: <" + LUBM_PREFIX + "> \n" + "SELECT * WHERE \n" + "{ \n"
            + "  ?graduateStudent a lubm:GraduateStudent . \n" + "  ?underGradUniversity a lubm:University . \n"
            + "  ?graduateStudent lubm:undergraduateDegreeFrom ?underGradUniversity . \n" + "}";

    final String query2 = "PREFIX lubm: <" + LUBM_PREFIX + "> \n" + "SELECT * WHERE \n" + "{ \n"
            + "  ?graduateStudent a lubm:GraduateStudent . \n" + "  ?underGradUniversity a lubm:University . \n"
            + "  ?graduateStudent lubm:undergraduateDegreeFrom ?underGradUniversity . \n" + "}";

    final String[] addArgs = new String[] { "--ryaInstance", "" + ryaInstance, "--kafkaHostname",
            kafka.getKafkaHostname(), "--kafkaPort", kafka.getKafkaPort(), "--query", query, "--isActive",
            "true", "--isInsert", "false" };

    final String[] addArgs2 = new String[] { "--ryaInstance", "" + ryaInstance, "--kafkaHostname",
            kafka.getKafkaHostname(), "--kafkaPort", kafka.getKafkaPort(), "--query", query2, "--isActive",
            "true", "--isInsert", "false" };

    // Execute the command.
    final AddQueryCommand command = new AddQueryCommand();
    command.execute(addArgs);//from ww w . ja v  a  2 s .  com
    // Add the same query twice to confirm that joins aren't being performed
    // across both queries.
    command.execute(addArgs2);

    // Show that the query was added to the Query Repository.
    final Set<StreamsQuery> queries = queryRepo.list();
    assertEquals(2, queries.size());
    final StreamsQuery streamsQuery = queries.iterator().next();
    final UUID queryId = streamsQuery.getQueryId();
    assertEquals(query, queries.iterator().next().getSparql());

    // Load a file of statements into Kafka.
    final String visibilities = "";
    final String[] loadArgs = new String[] { "--ryaInstance", "" + ryaInstance, "--kafkaHostname",
            kafka.getKafkaHostname(), "--kafkaPort", kafka.getKafkaPort(), "--statementsFile",
            LUBM_FILE.toString(), "--visibilities", visibilities };

    // Load the file of statements into the Statements topic.
    new LoadStatementsCommand().execute(loadArgs);

    final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
    final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);

    final TopologyFactory factory = new TopologyFactory();
    final TopologyBuilder builder = factory.build(query, statementsTopic, resultsTopic,
            new RandomUUIDFactory());

    // Start the streams program.
    final Properties props = kafka.createBootstrapServerConfig();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, UUID.randomUUID().toString());
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    final AtomicReference<String> errorMessage = new AtomicReference<>();
    final KafkaStreams streams = new KafkaStreams(builder, new StreamsConfig(props));
    streams.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            final String stackTrace = ExceptionUtils.getStackTrace(throwable);
            errorMessage.getAndSet("Kafka Streams threw an uncaught exception in thread (" + thread.getName()
                    + "): " + stackTrace);
        }
    });
    streams.cleanUp();
    try {
        streams.start();

        // Wait for the streams application to start. Streams only see data after their consumers are connected.
        Thread.sleep(6000);

        // Wait for the final results to appear in the output topic and verify the expected Binding Sets were found.
        try (Consumer<String, VisibilityBindingSet> consumer = KafkaTestUtil.fromStartConsumer(kafka,
                StringDeserializer.class, VisibilityBindingSetDeserializer.class)) {
            // Register the topic.
            consumer.subscribe(Arrays.asList(resultsTopic));

            // Poll for the result.
            final Set<VisibilityBindingSet> results = Sets.newHashSet(KafkaTestUtil.pollForResults(500,
                    2 * LUBM_EXPECTED_RESULTS_COUNT, LUBM_EXPECTED_RESULTS_COUNT, consumer));

            System.out.println("LUBM Query Results Count: " + results.size());
            // Show the correct binding sets results from the job.
            assertEquals(LUBM_EXPECTED_RESULTS_COUNT, results.size());
        }
    } finally {
        streams.close();
    }

    if (StringUtils.isNotBlank(errorMessage.get())) {
        fail(errorMessage.get());
    }
}

From source file:haven.Utils.java

private static void dumptg(ThreadGroup tg, PrintWriter out, int indent) {
    for (int o = 0; o < indent; o++)
        out.print("    ");
    out.println("G: \"" + tg.getName() + "\"");
    Thread[] ths = new Thread[tg.activeCount() * 2];
    ThreadGroup[] tgs = new ThreadGroup[tg.activeGroupCount() * 2];
    int nt = tg.enumerate(ths, false);
    int ng = tg.enumerate(tgs, false);
    for (int i = 0; i < nt; i++) {
        Thread ct = ths[i];
        for (int o = 0; o < indent + 1; o++)
            out.print("    ");
        out.println("T: \"" + ct.getName() + "\"");
    }/*from  w  w  w .j av  a 2 s .c  o  m*/
    for (int i = 0; i < ng; i++) {
        ThreadGroup cg = tgs[i];
        dumptg(cg, out, indent + 1);
    }
}

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

private synchronized static void asyncFetchConversationToken(final Context context) {
    Thread thread = new Thread() {
        @Override/*from www . ja v  a2s. c  om*/
        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:eu.stratosphere.nephele.profiling.impl.TaskManagerProfilerImpl.java

public void registerUserThreadForCPUProfiling(Environment environment, Thread userThread) {

    synchronized (this.monitoredThreads) {

        final EnvironmentThreadSet environmentThreadList = this.monitoredThreads.get(environment);
        if (environmentThreadList == null) {
            LOG.error("Trying to register " + userThread.getName() + " but no main thread found!");
            return;
        }/* w w w .  j a v a  2s. c  o m*/

        environmentThreadList.addUserThread(this.tmx, userThread);
    }

}

From source file:eu.stratosphere.nephele.profiling.impl.TaskManagerProfilerImpl.java

public void unregisterUserThreadFromCPUProfiling(Environment environment, Thread userThread) {

    synchronized (this.monitoredThreads) {

        final EnvironmentThreadSet environmentThreadSet = this.monitoredThreads.get(environment);
        if (environmentThreadSet == null) {
            LOG.error("Trying to unregister " + userThread.getName() + " but no main thread found!");
            return;
        }//from   w w w. j  a  va  2  s  .  co  m

        environmentThreadSet.removeUserThread(userThread);
    }

}

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);
        }//  ww w. ja v  a  2  s  . com
    };
    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.sonatype.nexus.perftest.ClientSwarm.java

public void stop() throws InterruptedException {
    for (Thread thread : threads) {
        for (int i = 0; i < 3 && thread.isAlive(); i++) {
            thread.interrupt();/*from  w w w .  jav a2 s  .c o m*/
            thread.join(1000L);
        }
        if (thread.isAlive()) {
            StringBuilder sb = new StringBuilder(
                    String.format("Thread %s ignored interrupt flag\n", thread.getName()));
            for (StackTraceElement f : thread.getStackTrace()) {
                sb.append("\t").append(f.toString()).append("\n");
            }
            System.err.println(sb.toString());
        }
    }
}