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:org.apache.nifi.processors.standard.ExecuteProcess.java

@OnScheduled
public void setupExecutor(final ProcessContext context) {
    executor = Executors.newFixedThreadPool(context.getMaxConcurrentTasks() * 2, new ThreadFactory() {
        private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

        @Override//ww  w  . ja v a2s.  c o  m
        public Thread newThread(final Runnable r) {
            final Thread t = defaultFactory.newThread(r);
            t.setName("ExecuteProcess " + getIdentifier() + " Task");
            return t;
        }
    });
}

From source file:com.baidu.fsg.uid.utils.NamingThreadFactory.java

@Override
public Thread newThread(Runnable r) {
    Thread thread = new Thread(r);
    thread.setDaemon(this.daemon);

    // If there is no specified name for thread, it will auto detect using the invoker classname instead.
    // Notice that auto detect may cause some performance overhead
    String prefix = this.name;
    if (StringUtils.isBlank(prefix)) {
        prefix = getInvoker(2);//w w  w.  j a  v  a  2s.  c o m
    }
    thread.setName(prefix + "-" + getSequence(prefix));

    // no specified uncaughtExceptionHandler, just do logging.
    if (this.uncaughtExceptionHandler != null) {
        thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler);
    } else {
        thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e);
            }
        });
    }

    return thread;
}

From source file:de.dkfz.roddy.core.Analysis.java

/**
 * Runs the passed execution context in a separate thread. The context level is taken from the passed object.
 *
 * @param ec The execution context which will be context in a separate thread.
 *///  ww w  .  j  a  v a  2  s .co  m
public void runDeferredContext(final ExecutionContext ec) {
    //        ThreadGroup
    Thread t = new Thread(() -> {
        executeRun(ec);
    });
    t.setName(String.format("Deferred execution context execution for pid %s", ec.getDataSet().getId()));
    t.start();
}

From source file:com.github.nethad.clustermeister.provisioning.jppf.LocalDriverBuilder.java

@Override
protected ClustermeisterLauncher doBuild() {
    JPPFDriverConfigurationSource.serverPort = serverPort;
    JPPFDriverConfigurationSource.managementPort = managementPort;
    JPPFDriverConfigurationSource.jvmOptions = configuration
            .getString(ConfigurationKeys.JVM_OPTIONS_LOCAL_DRIVER, "");
    Map<String, String> loadBalancingConfigValues = new DriverLoadBalancing(configuration)
            .getLoadBalancingConfigValues();
    if (loadBalancingConfigValues.isEmpty()) {
        //                logger.info("No load balancing settings set.");
    } else {//w  ww.j av  a  2 s .com
        for (Map.Entry<String, String> entry : loadBalancingConfigValues.entrySet()) {
            //                    logger.info("{} => {}", entry.getKey(), entry.getValue());
        }
    }
    JPPFDriverConfigurationSource.loadBalancing = new DriverLoadBalancing(configuration)
            .getLoadBalancingConfigValues();
    final ClustermeisterLauncher launcher = new ClustermeisterDriverLauncher(true);
    final AtomicBoolean initialized = new AtomicBoolean(false);
    final Monitor initializationMonitor = new Monitor(false);
    final Monitor.Guard isInitialized = new Monitor.Guard(initializationMonitor) {
        @Override
        public boolean isSatisfied() {
            return initialized.get();
        }
    };
    launcher.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            initializationMonitor.enter();
            try {
                initialized.set(true);
            } finally {
                initializationMonitor.leave();
            }
        }
    });
    Thread driverThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                launcher.doLaunch(true, ClustermeisterProcessLauncher.StreamSink.LOG);
            } catch (Throwable ex) {
                logger.warn("Execption from local driver thread.", ex);
            }
        }
    });
    driverThread.setName(String.format("%s-%s", DRIVER_THREAD_NAME, driverThread.getId()));
    driverThread.start();

    //wait for driver to initialize.
    initializationMonitor.enter();
    try {
        try {
            initializationMonitor.waitFor(isInitialized);
        } catch (InterruptedException ex) {
            logger.warn("Interrupted while waiting for local driver to initialize! "
                    + "Initialization may not be complete.", ex);
        }
    } finally {
        initializationMonitor.leave();
    }
    return launcher;
}

From source file:eu.europa.fisheries.uvms.rules.service.mapper.fact.xpath.util.XPathRepositoryTest.java

@Test
@SneakyThrows/*w ww.  j av  a2s  .c om*/
public void testConcurrencyNotTemperingWithRepositoryValues() {

    final int expectedFinalFactListSize = factList.size();

    // Threads creation
    Thread thread1 = new Thread(getRunnable(1, 0));
    thread1.setName("Thread1");
    Thread thread2 = new Thread(getRunnable(2, 1000));
    thread2.setName("Thread2");
    Thread thread3 = new Thread(getRunnable(3, 500));
    thread3.setName("Thread3");
    Thread thread4 = new Thread(getRunnable(1, 0));
    thread4.setName("Thread4");
    Thread thread5 = new Thread(getRunnable(2, 1000));
    thread5.setName("Thread5");
    Thread thread6 = new Thread(getRunnable(3, 500));
    thread6.setName("Thread6");
    Thread thread7 = new Thread(getRunnable(1, 0));
    thread7.setName("Thread7");
    Thread thread8 = new Thread(getRunnable(2, 1000));
    thread8.setName("Thread8");
    Thread thread9 = new Thread(getRunnable(3, 500));
    thread9.setName("Thread9");

    // Threads start
    thread1.start();
    repo.clear(factList);
    thread2.start();
    repo.clear(factList);
    thread3.start();
    repo.clear(factList);
    thread4.start();
    repo.clear(factList);
    thread5.start();
    repo.clear(factList);
    thread6.start();
    repo.clear(factList);
    thread7.start();
    repo.clear(factList);
    thread8.start();
    repo.clear(factList);
    thread9.start();
    repo.clear(factList);

    Thread.sleep(2000);

    final Map<Integer, Map<String, String>> xpathsMap = repo.getXpathsMap();
    for (Map.Entry<Integer, Map<String, String>> outMap : xpathsMap.entrySet()) {
        for (Map.Entry<String, String> inMap : outMap.getValue().entrySet()) {
            String value = inMap.getValue();
            testValueForDoubles(value);
        }
    }

    final int realFinalFactListSize = factList.size();
    boolean success = true;
    if (MapUtils.isNotEmpty(failedMap)) {
        for (Map.Entry<String, String> val : failedMap.entrySet()) {
            System.out.println("\nFailed value : " + val.getValue() + " Result : " + val.getKey());
            success = false;
        }
    } else {
        System.out.println("Failed Map is empty. No errors..");
    }
    assertTrue(success);
    System.out.println("Initial fact size : [" + expectedFinalFactListSize + "]. End fact size : ["
            + realFinalFactListSize + "]");

}

From source file:org.apache.cassandra.repair.RepairRunnable.java

protected void runMayThrow() throws Exception {
    final TraceState traceState;

    final String tag = "repair:" + cmd;

    final AtomicInteger progress = new AtomicInteger();
    final int totalProgress = 3 + options.getRanges().size(); // calculate neighbors, validation, prepare for repair + number of ranges to repair

    String[] columnFamilies = options.getColumnFamilies()
            .toArray(new String[options.getColumnFamilies().size()]);
    Iterable<ColumnFamilyStore> validColumnFamilies = storageService.getValidColumnFamilies(false, false,
            keyspace, columnFamilies);// w ww  .  j  ava  2  s . co m

    final long startTime = System.currentTimeMillis();
    String message = String.format("Starting repair command #%d, repairing keyspace %s with %s", cmd, keyspace,
            options);
    logger.info(message);
    fireProgressEvent(tag, new ProgressEvent(ProgressEventType.START, 0, 100, message));
    if (options.isTraced()) {
        StringBuilder cfsb = new StringBuilder();
        for (ColumnFamilyStore cfs : validColumnFamilies)
            cfsb.append(", ").append(cfs.keyspace.getName()).append(".").append(cfs.name);

        UUID sessionId = Tracing.instance.newSession(Tracing.TraceType.REPAIR);
        traceState = Tracing.instance.begin("repair",
                ImmutableMap.of("keyspace", keyspace, "columnFamilies", cfsb.substring(2)));
        Tracing.traceRepair(message);
        traceState.enableActivityNotification(tag);
        for (ProgressListener listener : listeners)
            traceState.addProgressListener(listener);
        Thread queryThread = createQueryThread(cmd, sessionId);
        queryThread.setName("RepairTracePolling");
        queryThread.start();
    } else {
        traceState = null;
    }

    final Set<InetAddress> allNeighbors = new HashSet<>();
    Map<Range, Set<InetAddress>> rangeToNeighbors = new HashMap<>();
    try {
        for (Range<Token> range : options.getRanges()) {
            Set<InetAddress> neighbors = ActiveRepairService.getNeighbors(keyspace, range,
                    options.getDataCenters(), options.getHosts());
            rangeToNeighbors.put(range, neighbors);
            allNeighbors.addAll(neighbors);
        }
        progress.incrementAndGet();
    } catch (IllegalArgumentException e) {
        logger.error("Repair failed:", e);
        fireErrorAndComplete(tag, progress.get(), totalProgress, e.getMessage());
        return;
    }

    // Validate columnfamilies
    List<ColumnFamilyStore> columnFamilyStores = new ArrayList<>();
    try {
        Iterables.addAll(columnFamilyStores, validColumnFamilies);
        progress.incrementAndGet();
    } catch (IllegalArgumentException e) {
        fireErrorAndComplete(tag, progress.get(), totalProgress, e.getMessage());
        return;
    }

    String[] cfnames = new String[columnFamilyStores.size()];
    for (int i = 0; i < columnFamilyStores.size(); i++) {
        cfnames[i] = columnFamilyStores.get(i).name;
    }

    final UUID parentSession = UUIDGen.getTimeUUID();
    SystemDistributedKeyspace.startParentRepair(parentSession, keyspace, cfnames, options.getRanges());
    long repairedAt;
    try {
        ActiveRepairService.instance.prepareForRepair(parentSession, allNeighbors, options, columnFamilyStores);
        repairedAt = ActiveRepairService.instance.getParentRepairSession(parentSession).getRepairedAt();
        progress.incrementAndGet();
    } catch (Throwable t) {
        SystemDistributedKeyspace.failParentRepair(parentSession, t);
        fireErrorAndComplete(tag, progress.get(), totalProgress, t.getMessage());
        return;
    }

    // Set up RepairJob executor for this repair command.
    final ListeningExecutorService executor = MoreExecutors.listeningDecorator(
            new JMXConfigurableThreadPoolExecutor(options.getJobThreads(), Integer.MAX_VALUE, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("Repair#" + cmd), "internal"));

    List<ListenableFuture<RepairSessionResult>> futures = new ArrayList<>(options.getRanges().size());
    for (Range<Token> range : options.getRanges()) {
        final RepairSession session = ActiveRepairService.instance.submitRepairSession(parentSession, range,
                keyspace, options.getParallelism(), rangeToNeighbors.get(range), repairedAt, executor, cfnames);
        if (session == null)
            continue;
        // After repair session completes, notify client its result
        Futures.addCallback(session, new FutureCallback<RepairSessionResult>() {
            public void onSuccess(RepairSessionResult result) {
                String message = String.format("Repair session %s for range %s finished", session.getId(),
                        session.getRange().toString());
                logger.info(message);
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.PROGRESS, progress.incrementAndGet(),
                        totalProgress, message));
            }

            public void onFailure(Throwable t) {
                String message = String.format("Repair session %s for range %s failed with error %s",
                        session.getId(), session.getRange().toString(), t.getMessage());
                logger.error(message, t);
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.PROGRESS, progress.incrementAndGet(),
                        totalProgress, message));
            }
        });
        futures.add(session);
    }

    // After all repair sessions completes(successful or not),
    // run anticompaction if necessary and send finish notice back to client
    final Collection<Range<Token>> successfulRanges = new ArrayList<>();
    final AtomicBoolean hasFailure = new AtomicBoolean();
    final ListenableFuture<List<RepairSessionResult>> allSessions = Futures.successfulAsList(futures);
    ListenableFuture anticompactionResult = Futures.transform(allSessions,
            new AsyncFunction<List<RepairSessionResult>, Object>() {
                @SuppressWarnings("unchecked")
                public ListenableFuture apply(List<RepairSessionResult> results) throws Exception {
                    // filter out null(=failed) results and get successful ranges
                    for (RepairSessionResult sessionResult : results) {
                        if (sessionResult != null) {
                            successfulRanges.add(sessionResult.range);
                        } else {
                            hasFailure.compareAndSet(false, true);
                        }
                    }
                    return ActiveRepairService.instance.finishParentSession(parentSession, allNeighbors,
                            successfulRanges);
                }
            });
    Futures.addCallback(anticompactionResult, new FutureCallback<Object>() {
        public void onSuccess(Object result) {
            SystemDistributedKeyspace.successfulParentRepair(parentSession, successfulRanges);
            if (hasFailure.get()) {
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.ERROR, progress.get(), totalProgress,
                        "Some repair failed"));
            } else {
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.SUCCESS, progress.get(),
                        totalProgress, "Repair completed successfully"));
            }
            repairComplete();
        }

        public void onFailure(Throwable t) {
            fireProgressEvent(tag,
                    new ProgressEvent(ProgressEventType.ERROR, progress.get(), totalProgress, t.getMessage()));
            SystemDistributedKeyspace.failParentRepair(parentSession, t);
            repairComplete();
        }

        private void repairComplete() {
            String duration = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - startTime,
                    true, true);
            String message = String.format("Repair command #%d finished in %s", cmd, duration);
            fireProgressEvent(tag,
                    new ProgressEvent(ProgressEventType.COMPLETE, progress.get(), totalProgress, message));
            logger.info(message);
            if (options.isTraced() && traceState != null) {
                for (ProgressListener listener : listeners)
                    traceState.removeProgressListener(listener);
                // Because DebuggableThreadPoolExecutor#afterExecute and this callback
                // run in a nondeterministic order (within the same thread), the
                // TraceState may have been nulled out at this point. The TraceState
                // should be traceState, so just set it without bothering to check if it
                // actually was nulled out.
                Tracing.instance.set(traceState);
                Tracing.traceRepair(message);
                Tracing.instance.stopSession();
            }
            executor.shutdownNow();
        }
    });
}

From source file:org.pentaho.reporting.platform.plugin.async.PentahoAsyncExecutor.java

/**
 * @param capacity               thread pool capacity
 * @param autoSchedulerThreshold quantity of rows after which reports are automatically scheduled
 *///from w  w w  . j av  a  2  s.  c  om
public PentahoAsyncExecutor(final int capacity, final int autoSchedulerThreshold) {
    this.autoSchedulerThreshold = autoSchedulerThreshold;
    log.info("Initialized reporting async execution fixed thread pool with capacity: " + capacity);
    executorService = new DelegatedListenableExecutor(new ThreadPoolExecutor(capacity, capacity, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = Executors.defaultThreadFactory().newThread(r);
                    thread.setDaemon(true);
                    thread.setName("PentahoAsyncExecutor Thread Pool");
                    return thread;
                }
            }));
    PentahoSystem.addLogoutListener(this);
    this.writeToJcrListeners = new ConcurrentHashMap<>();
    this.schedulingLocationListener = new MemorizeSchedulingLocationListener();
}

From source file:org.apache.hadoop.hbase.master.cleaner.HFileCleaner.java

/**
 * Start threads for hfile deletion//from  w  w w.ja  v a  2 s . co m
 */
private void startHFileDeleteThreads() {
    final String n = Thread.currentThread().getName();
    running = true;
    // start thread for large file deletion
    Thread large = new Thread() {
        @Override
        public void run() {
            consumerLoop(largeFileQueue);
        }
    };
    large.setDaemon(true);
    large.setName(n + "-HFileCleaner.large-" + System.currentTimeMillis());
    large.start();
    LOG.debug("Starting hfile cleaner for large files: " + large.getName());
    threads.add(large);

    // start thread for small file deletion
    Thread small = new Thread() {
        @Override
        public void run() {
            consumerLoop(smallFileQueue);
        }
    };
    small.setDaemon(true);
    small.setName(n + "-HFileCleaner.small-" + System.currentTimeMillis());
    small.start();
    LOG.debug("Starting hfile cleaner for small files: " + small.getName());
    threads.add(small);
}

From source file:org.hyperic.lather.server.LatherServlet.java

private void doServiceCall(HttpServletRequest req, HttpServletResponse resp, String methName, LatherValue args,
        LatherXCoder xCoder, LatherContext ctx) throws IOException {

    final LatherDispatcher latherDispatcher = Bootstrap.getBean(LatherDispatcher.class);
    final ServiceCaller caller = new ServiceCaller(resp, xCoder, ctx, methName, args, latherDispatcher);
    final Thread currentThread = Thread.currentThread();
    final String threadName = currentThread.getName();

    try {/*from  w  ww .j  a  v  a 2s .  c o m*/
        currentThread.setName(methName + "-" + ids.getAndIncrement());
        LatherThreadMonitor.get().register(caller);
        caller.run();
        if (currentThread.isInterrupted()) {
            throw new InterruptedException();
        }
    } catch (InterruptedException exc) {
        log.warn("Interrupted while trying to execute lather method=" + methName + " from ip="
                + ctx.getCallerIP());
    } finally {
        caller.markFinished();
        currentThread.setName(threadName);
    }
}

From source file:mServer.crawler.sender.MediathekNdr.java

@Override
protected void addToList() {
    //<broadcast id="1391" site="ndrfernsehen">45 Min</broadcast>
    final String ADRESSE = "http://www.ndr.de/mediathek/sendungen_a-z/index.html";
    final String MUSTER_URL1 = "<li><a href=\"/mediathek/mediatheksuche105_broadcast-";
    listeThemen.clear();/*from   w w w  .ja  va 2 s  .c om*/

    meldungStart();

    MSStringBuilder seite = new MSStringBuilder(Const.STRING_BUFFER_START_BUFFER);
    final GetUrl getUrlIo = new GetUrl(getWartenSeiteLaden());
    seite = getUrlIo.getUri(SENDERNAME, ADRESSE, StandardCharsets.UTF_8, 5 /* versuche */, seite,
            ""/* meldung */);
    int pos = 0;
    int pos1;
    int pos2;
    String url = "";
    String thema = "";
    while ((pos = seite.indexOf(MUSTER_URL1, pos)) != -1) {
        try {
            pos += MUSTER_URL1.length();
            pos1 = pos;
            if ((pos2 = seite.indexOf("\"", pos)) != -1) {
                url = seite.substring(pos1, pos2);
            }
            pos1 = seite.indexOf(">", pos);
            pos2 = seite.indexOf("<", pos);
            if (pos1 != -1 && pos2 != -1 && pos1 < pos2) {
                thema = seite.substring(pos1 + 1, pos2);
            }
            if (url.isEmpty()) {
                Log.errorLog(210367600, "keine Url");
                continue;
            }
            String url_ = "http://www.ndr.de/mediathek/mediatheksuche105_broadcast-" + url;
            String[] add = new String[] { url_, thema };
            if (CrawlerTool.loadLongMax()) {
                if (!alleSeiteSuchen(url_, thema)) {
                    // dann halt so versuchen
                    listeThemen.addUrl(add);
                }
            } else {
                listeThemen.addUrl(add);
            }
        } catch (Exception ex) {
            Log.errorLog(332945670, ex);
        }
    }
    // noch "Verpasst" fr die letzten Tage einfgen
    // http://www.ndr.de/mediathek/sendung_verpasst/epg1490_date-2014-05-17.html
    // http://www.ndr.de/mediathek/sendung_verpasst/epg1490_date-2014-05-17_display-onlyvideo.html
    FastDateFormat formatter1 = FastDateFormat.getInstance("yyyy-MM-dd");
    FastDateFormat formatter2 = FastDateFormat.getInstance("dd.MM.yyyy");
    final int maxTage = CrawlerTool.loadLongMax() ? 30 : 20;
    for (int i = 0; i < maxTage; ++i) {
        // https://www.ndr.de/mediathek/sendung_verpasst/epg1490_date-2015-09-05_display-all.html
        final String URL = "http://www.ndr.de/mediathek/sendung_verpasst/epg1490_date-";
        final String tag = formatter1.format(new Date().getTime() - (1000 * 60 * 60 * 24 * i));
        final String date = formatter2.format(new Date().getTime() - (1000 * 60 * 60 * 24 * i));
        //String urlString = URL + tag + "_display-onlyvideo.html"; --> stimmt leider nicht immer
        final String urlString = URL + tag + "_display-all.html";
        listeThemen.addUrl(new String[] { urlString, date });
    }

    if (Config.getStop()) {
        meldungThreadUndFertig();
    } else if (listeThemen.isEmpty()) {
        meldungThreadUndFertig();
    } else {
        meldungAddMax(listeThemen.size());
        for (int t = 0; t < getMaxThreadLaufen(); ++t) {
            Thread th = new ThemaLaden();
            th.setName(SENDERNAME + t);
            th.start();
        }
    }
}