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.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/*from w  ww  .  j a va 2s .  c om*/
        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:mServer.crawler.sender.MediathekKika.java

@Override
protected void addToList() {

    meldungStart();/*from  w w  w.j a  va2  s . c o m*/
    if (CrawlerTool.loadLongMax()) {
        addToListNormal();
    }
    addToListAllVideo();

    if (Config.getStop()) {
        meldungThreadUndFertig();
    } else if (listeThemen.isEmpty() && listeAllVideos.isEmpty()) {
        meldungThreadUndFertig();
    } else {
        // dann den Sender aus der alten Liste lschen
        // URLs laufen nur begrenzte Zeit
        // delSenderInAlterListe(SENDERNAME); brauchts wohl nicht mehr
        meldungAddMax(listeThemen.size() + listeAllVideos.size());
        for (int t = 0; t <= getMaxThreadLaufen(); ++t) {
            Thread th = new ThemaLaden();
            th.setName(SENDERNAME + t);
            th.start();
        }
    }
}

From source file:eu.wordnice.wnconsole.WNCUtils.java

protected static Thread createHIOThread(final HIOServer serv, final Handler.TwoVoidHandler<Thread, HIO> handl,
        final boolean debug, final long timeout, final Logger lg) {
    return new Thread() {
        @Override// w  w w  . j a v a  2s .c  o  m
        public void run() {
            serv.onAcceptRaw(new Handler.OneVoidHandler<Socket>() {
                @Override
                public void handle(Socket sock) {
                    try {
                        final HIO hio = new HIO(sock);
                        Thread rt = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    hio.decode(false, timeout);
                                    handl.handle(this, hio);
                                } catch (Throwable th) {
                                    if (debug) {
                                        lg.info("Error while accepting client from "
                                                + hio.sock.getInetAddress().toString() + ", path [" + hio.PATH
                                                + "], error " + th.getMessage());
                                    }
                                }
                                try {
                                    hio.close();
                                } catch (Throwable tign) {
                                }
                            }
                        };
                        tid++;
                        rt.setName("WNC HIO Handle " + tid);
                        rt.start();
                    } catch (Throwable t) {
                    }
                }
            });
        }
    };
}

From source file:org.jumpmind.symmetric.service.impl.NodeCommunicationService.java

protected ThreadPoolExecutor getExecutor(final CommunicationType communicationType) {
    ThreadPoolExecutor service = executors.get(communicationType);

    String threadCountParameter = "";
    switch (communicationType) {
    case PULL://from  ww w  . ja  va  2s  . c  o m
        threadCountParameter = ParameterConstants.PULL_THREAD_COUNT_PER_SERVER;
        break;
    case PUSH:
        threadCountParameter = ParameterConstants.PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case FILE_PULL:
        threadCountParameter = ParameterConstants.FILE_PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case FILE_PUSH:
        threadCountParameter = ParameterConstants.FILE_PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case EXTRACT:
        threadCountParameter = ParameterConstants.INITIAL_LOAD_EXTRACT_THREAD_COUNT_PER_SERVER;
        break;
    default:
        break;
    }
    int threadCount = parameterService.getInt(threadCountParameter, 1);

    if (service != null && service.getCorePoolSize() != threadCount) {
        log.info("{} has changed from {} to {}.  Restarting thread pool",
                new Object[] { threadCountParameter, service.getCorePoolSize(), threadCount });
        stop();
        service = null;
    }

    if (service == null) {
        synchronized (this) {
            service = executors.get(communicationType);
            if (service == null) {
                if (threadCount <= 0) {
                    log.warn("{}={} is not a valid value. Defaulting to 1", threadCountParameter, threadCount);
                    threadCount = 1;
                } else if (threadCount > 1) {
                    log.info("{} will use {} threads", communicationType.name().toLowerCase(), threadCount);
                }
                service = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
                    final AtomicInteger threadNumber = new AtomicInteger(1);
                    final String namePrefix = parameterService.getEngineName().toLowerCase() + "-"
                            + communicationType.name().toLowerCase() + "-";

                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setName(namePrefix + threadNumber.getAndIncrement());
                        if (t.isDaemon()) {
                            t.setDaemon(false);
                        }
                        if (t.getPriority() != Thread.NORM_PRIORITY) {
                            t.setPriority(Thread.NORM_PRIORITY);
                        }
                        return t;
                    }
                });
                executors.put(communicationType, service);
            }
        }
    }
    return service;
}

From source file:com.sworddance.taskcontrol.TestTaskControl.java

private void startTaskControl(TaskControl taskControl, TaskGroup<?> taskGroup) throws InterruptedException {
    // additional test that addTaskGroup after TaskControl start will work.
    taskControl.addTaskGroup(taskGroup);
    Thread t = new Thread(taskControl);
    taskControl.setStayActive(false);/* www.ja  v  a2 s .  co m*/
    t.setName("TaskControl");
    t.start();
    t.join();
    assertFalse(t.isAlive());
}

From source file:edu.umass.cs.gigapaxos.PaxosPacketBatcher.java

public void start() {
    Thread me = (new Thread(this));
    me.setName(PaxosPacketBatcher.class.getSimpleName() + this.paxosManager.getMyID());
    me.start();//  ww w.  j  a v  a2 s .  co m
}

From source file:org.jumpmind.symmetric.service.impl.PushService.java

public void start() {
    nodeChannelExtractForPushWorker = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix = parameterService.getEngineName().toLowerCase() + "-extract-for-push-";

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);//  w ww .  j  a  v a  2s .c o m
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    });

    nodeChannelTransportForPushWorker = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix = parameterService.getEngineName().toLowerCase() + "-push-";

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    });
}

From source file:org.apache.nifi.processors.standard.ListenTCPRecord.java

@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    this.port = context.getProperty(PORT).evaluateAttributeExpressions().asInteger();

    final int readTimeout = context.getProperty(READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    final int maxSocketBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B)
            .intValue();// w w w  .j a  v a 2  s .c  o m
    final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
    final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER)
            .asControllerService(RecordReaderFactory.class);

    // if the Network Interface Property wasn't provided then a null InetAddress will indicate to bind to all interfaces
    final InetAddress nicAddress;
    final String nicAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions()
            .getValue();
    if (!StringUtils.isEmpty(nicAddressStr)) {
        NetworkInterface netIF = NetworkInterface.getByName(nicAddressStr);
        nicAddress = netIF.getInetAddresses().nextElement();
    } else {
        nicAddress = null;
    }

    SSLContext sslContext = null;
    SslContextFactory.ClientAuth clientAuth = null;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    if (sslContextService != null) {
        final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
        sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.valueOf(clientAuthValue));
        clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
    }

    // create a ServerSocketChannel in non-blocking mode and bind to the given address and port
    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.bind(new InetSocketAddress(nicAddress, port));

    this.dispatcher = new SocketChannelRecordReaderDispatcher(serverSocketChannel, sslContext, clientAuth,
            readTimeout, maxSocketBufferSize, maxConnections, recordReaderFactory, socketReaders, getLogger());

    // start a thread to run the dispatcher
    final Thread readerThread = new Thread(dispatcher);
    readerThread.setName(getClass().getName() + " [" + getIdentifier() + "]");
    readerThread.setDaemon(true);
    readerThread.start();
}

From source file:io.stallion.boot.Booter.java

public void boot(String[] args, StallionJavaPlugin[] plugins) throws Exception {

    // Load the plugin jars, to get additional actions
    String targetPath = new File(".").getAbsolutePath();
    for (String arg : args) {
        if (arg.startsWith("-targetPath=")) {
            targetPath = StringUtils.split(arg, "=", 2)[1];
        }/*from  ww w  . jav a2 s.  c o  m*/
    }
    if (!new File(targetPath).isDirectory() || empty(targetPath) || targetPath.equals("/")
            || targetPath.equals("/.")) {
        throw new CommandException(
                "You ran stallion with the target path " + targetPath + " but that is not a valid folder.");
    }

    PluginRegistry.loadWithJavaPlugins(targetPath, plugins);
    List<StallionRunAction> actions = new ArrayList(builtinActions);
    actions.addAll(PluginRegistry.instance().getAllPluginDefinedStallionRunActions());

    // Load the action executor
    StallionRunAction action = null;
    for (StallionRunAction anAction : actions) {
        if (empty(anAction.getActionName())) {
            throw new UsageException(
                    "The action class " + anAction.getClass().getName() + " has an empty action name");
        }
        if (args.length > 0 && anAction.getActionName().equals(args[0])) {
            action = anAction;
        }
    }
    if (action == null) {
        String msg = "\n\nError! You must pass in a valid action as the first command line argument. For example:\n\n"
                + ">stallion serve -port=8090 -targetPath=~/my-stallion-site\n";
        if (args.length > 0) {
            msg += "\n\nYou passed in '" + args[0] + "', which is not a valid action.\n";
        }
        msg += "\nAllowed actions are:\n\n";
        for (StallionRunAction anAction : actions) {
            //Log.warn("Action: {0} {1} {2}", action, action.getActionName(), action.getHelp());
            msg += anAction.getActionName() + " - " + anAction.getHelp() + "\n";
        }
        msg += "\n\nYou can get help about an action by running: >stallion <action> help\n\n";
        System.err.println(msg);
        System.exit(1);
    }

    // Load the command line options
    CommandOptionsBase options = action.newCommandOptions();

    CmdLineParser parser = new CmdLineParser(options);

    if (args.length > 1 && "help".equals(args[1])) {
        System.out.println(action.getActionName() + " - " + action.getHelp() + "\n\n");
        System.out.println("\n\nOptions for command " + action.getActionName() + "\n\n");
        parser.printUsage(System.out);
        System.exit(0);
    }

    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("\n\nError!\n\n" + e.getMessage());
        System.err.println("\n\nAllowed options: \n");
        parser.printUsage(System.err);
        System.err.println("\n");
        System.exit(1);
    }

    options.setExtraPlugins(Arrays.asList(plugins));

    if (!empty(options.getLogLevel())) {
        try {
            Log.setLogLevel(Level.parse(options.getLogLevel()));
        } catch (IllegalArgumentException e) {
            System.err.println("\nError! Invalid log level: " + options.getLogLevel() + "\n\n"
                    + CommandOptionsBase.ALLOWED_LEVELS);
            System.exit(1);
        }
    }
    if (empty(options.getTargetPath())) {
        options.setTargetPath(new File(".").getAbsolutePath());
    }

    // Shutdown hooks
    Thread shutDownHookThread = new Thread() {
        public void run() {
            try {
                Unirest.shutdown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    shutDownHookThread.setName("stallion-shutdown-hook");
    Runtime.getRuntime().addShutdownHook(shutDownHookThread);

    // Execute the action
    action.loadApp(options);
    for (StallionJavaPlugin plugin : PluginRegistry.instance().getJavaPluginByName().values()) {
        plugin.preExecuteAction(action.getActionName(), options);
    }
    action.execute(options);

    if (!AppContextLoader.isNull()) {
        AppContextLoader.shutdown();
    }

}

From source file:bq.jpa.demo.lock.LockTester.java

public void test3() {
    System.out.println("---- modify salary while do statistic ----");

    Thread thread1 = new Thread(new Runnable() {

        @Override/*from w ww  .  j  a  va 2  s . c o  m*/
        public void run() {
            service.doModify1();
        }
    });
    Thread thread2 = new Thread(new Runnable() {

        @Override
        public void run() {
            service.doModify2();
        }
    });

    thread1.setName("modifythread1");
    thread2.setName("modifythread2");
    try {
        thread2.start();
        Thread.sleep(1000);
        thread1.start();
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    try {
        thread1.join();
        thread2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}