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:com.jim.im.message.service.ApnClientUnit.java

/**
 * @param appId//  w  w w  .jav a2 s .c  o  m
 * @param env
 * @param pwd
 * @param bis
 */
private void startApnsClient(String appId, final ApnEnv env, String pwd, InputStream bis) {
    try {
        final ApnsClient<SimpleApnsPushNotification> apnsClient = new ApnsClient<>(bis, pwd);
        Thread task = new Thread(new ApnClientConnectTask(apnsClient, env.getHost(), appId));
        task.setName("ApnClientConnectTask_appId:" + appId);
        task.start();
        connectTasks.add(task);
        apnClients.put(appId, apnsClient);
    } catch (SSLException e) {
        logger.error("failed to get SSLContext, exist. appId: " + appId, e);
        System.exit(1);
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSConnectionPoolImplTest.java

@Test
public void testPoolWithMultipleThreads() {
    String testAppId = "multithreadTestApp";
    /**/*from w  w  w.j av a  2s. c  o m*/
     * create 5 threads each sending to 100 devices
     */
    int deviceCount = 100;
    int threadCount = 5;
    Map<String, String> payload = new LinkedHashMap<String, String>(100);
    for (int i = 0; i < deviceCount; i++) {
        payload.put("device:" + (i + 1), "JSON Payload{}:" + (i + 1));
    }
    objectFactory.clearCounter();
    APNSConnectionPoolImpl pool = APNSConnectionPoolImpl.getInstance();
    //initialize the pool with connections for all apps

    //    for (int i = 0; i < appIds.length; i++) {
    //      APNSConnection conn = pool.getConnection(appIds[i], true);
    //      pool.returnConnection(conn);
    //    }

    CountDownLatch countDownLatch = new CountDownLatch(threadCount);
    Executor executor = Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
        private AtomicInteger counter = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("TestThread:" + counter.getAndIncrement());
            return t;
        }
    });
    for (int i = 0; i < threadCount; i++) {
        executor.execute(new SimpleAPNSSenderThread(testAppId, true, payload, countDownLatch));
    }
    //wait for the threads to finish
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    int count = objectFactory.getCreatedCount(new APNSConnectionPoolImpl.APNSConnectionKey(testAppId, true));
    assertEquals("Object got created too many times", MAX_OBJECTS_PER_KEY, count);
}

From source file:net.bluehornreader.service.FeedManagerService.java

/**
 * Just creates the leader elector and lets it take over
 *///  w w  w .  j a  v a  2s . c o  m
@Override
public void run() {
    LOG.info("Starting LeaderElector ...");
    leaderElector = new LeaderElector(Config.getConfig().feedManagerTicksBeforeBecomingLeader,
            Config.getConfig().feedManagerTickInterval);
    Thread t = new Thread(leaderElector);
    t.setDaemon(true);
    t.setName("FeedManagerService/" + IP);
    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        LOG.error("Exception running LeaderElector", e);
    }
    LOG.info(String.format("FeedManagerService %s exiting", IP));
}

From source file:com.datatorrent.lib.io.WebSocketOutputOperator.java

private void openConnection() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    final AsyncHttpClientConfigBean config = new AsyncHttpClientConfigBean();
    config.setIoThreadMultiplier(ioThreadMultiplier);
    config.setApplicationThreadPool(Executors.newCachedThreadPool(new ThreadFactory() {
        @Override/*from  ww  w .j  av  a 2s .  co m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(ClassUtils.getShortClassName(this.getClass()) + "-AsyncHttpClient-" + count++);
            return t;
        }

    }));
    client = new AsyncHttpClient(config);
    uri = URI.create(uri.toString()); // force reparse after deserialization
    LOG.info("Opening URL: {}", uri);
    connection = client.prepareGet(uri.toString())
            .execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
                @Override
                public void onMessage(String string) {
                }

                @Override
                public void onOpen(WebSocket ws) {
                    LOG.debug("Connection opened");
                }

                @Override
                public void onClose(WebSocket ws) {
                    LOG.debug("Connection closed.");
                }

                @Override
                public void onError(Throwable t) {
                    LOG.error("Caught exception", t);
                }

            }).build()).get(5, TimeUnit.SECONDS);
}

From source file:org.rhq.core.system.SigarAccessHandler.java

SigarAccessHandler(SigarFactory sigarFactory) {
    this.sigarFactory = sigarFactory;
    sharedSigarLock = new ReentrantLock();
    localSigarLock = new ReentrantLock();
    scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        private ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();

        private AtomicInteger threadCounter = new AtomicInteger(0);

        @Override//from w w  w.  j  a v  a 2  s . co  m
        public Thread newThread(Runnable runnable) {
            Thread thread = defaultThreadFactory.newThread(runnable);
            thread.setName("SigarAccessHandler-" + threadCounter.incrementAndGet());
            // With daemon threads, there is no need to call #shutdown on the executor to let the JVM go down
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduledExecutorService.scheduleWithFixedDelay(new ThresholdChecker(), 1, 5, MINUTES);
    localSigarInstancesCount = 0;
    closed = false;
}

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.RamDiskAsyncLazyPersistService.java

private void addExecutorForVolume(final File volume) {
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override/*from  www  .j  a  v  a2s .  c o m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(threadGroup, r);
            t.setName("Async RamDisk lazy persist worker for volume " + volume);
            return t;
        }
    };

    ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_THREADS_PER_VOLUME, MAXIMUM_THREADS_PER_VOLUME,
            THREADS_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);

    // This can reduce the number of running threads
    executor.allowCoreThreadTimeOut(true);
    executors.put(volume, executor);
}

From source file:com.wallabystreet.kinjo.common.transport.protocol.jxta.JXTAServiceHandler.java

public void run() {
    JxtaBiDiPipe messagePipe = null;//from  w  w  w  .j av  a 2  s  .  c om
    while (!this.stop) {
        try {
            messagePipe = this.serverPipe.accept();
        } catch (IOException e) {
            log.warn(this.serviceDescriptor.getName() + ": I/O error while waiting for connection", e);
        }

        // Create a new session
        Thread handler = new Thread(new JXTAConnectionHandler(messagePipe));
        handler.setName(this.serviceDescriptor.getName() + "(connection handler)");
        handler.start();
    }
}

From source file:org.connectbot.util.UpdateHelper.java

/**
 * Constructor will automatically spawn thread to check for updates.
 * Recommended usage is <code>new UpdateHelper(this);</code> in the first
 * onCreate() of your app./*from www .j a  v a2s  . c  o  m*/
 */
public UpdateHelper(Context context) {
    this.context = context;

    try {
        // read current version information about this package
        PackageManager manager = context.getPackageManager();
        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
        this.packageName = info.packageName;
        this.versionCode = info.versionCode;
        this.versionName = info.versionName;

    } catch (Exception e) {
        Log.e(TAG, "Couldn't find package information in PackageManager", e);
        return;
    }

    // decide if we really need to check for update
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    String frequency;
    try {
        frequency = prefs.getString(PreferenceConstants.UPDATE, PreferenceConstants.UPDATE_DAILY);
    } catch (ClassCastException cce) {
        // Hm, somehow we got a long in there in the previous upgrades.
        frequency = PreferenceConstants.UPDATE_DAILY;
        Editor editor = prefs.edit();
        editor.putString(PreferenceConstants.UPDATE, frequency);
        editor.commit();
    }
    long lastChecked = prefs.getLong(PreferenceConstants.LAST_CHECKED, 0);
    long now = (System.currentTimeMillis() / 1000);
    long passed = now - lastChecked;

    boolean shouldCheck = false;
    if (PreferenceConstants.UPDATE_DAILY.equals(frequency)) {
        shouldCheck = (passed > 60 * 60 * 24);
    } else if (PreferenceConstants.UPDATE_WEEKLY.equals(frequency)) {
        shouldCheck = (passed > 60 * 60 * 24 * 7);
    }

    // place version information in user-agent string to be used later
    userAgent = String.format("%s/%s (%d, freq=%s, lang=%s)", packageName, versionName, versionCode, frequency,
            Locale.getDefault().getLanguage());

    if (shouldCheck) {
        // spawn thread to check for update
        // Note that this class should be marked final because a thread is started in the constructor.
        Thread updateThread = new Thread(this);
        updateThread.setName("UpdateHelper");
        updateThread.start();

        // update our last-checked time
        Editor editor = prefs.edit();
        editor.putLong(PreferenceConstants.LAST_CHECKED, now);
        editor.commit();

    }

}

From source file:org.apache.nifi.minifi.bootstrap.configuration.ingestors.FileChangeIngestor.java

@Override
public void start() {
    executorService = Executors.newScheduledThreadPool(1, new ThreadFactory() {
        @Override//w ww.j  ava 2  s. com
        public Thread newThread(final Runnable r) {
            final Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setName("File Change Notifier Thread");
            t.setDaemon(true);
            return t;
        }
    });
    this.executorService.scheduleWithFixedDelay(this, 0, pollingSeconds, DEFAULT_POLLING_PERIOD_UNIT);
}

From source file:org.apache.nifi.remote.client.http.HttpClient.java

public HttpClient(final SiteToSiteClientConfig config) {
    super(config);

    peerSelector = new PeerSelector(this, config.getPeerPersistenceFile());
    peerSelector.setEventReporter(config.getEventReporter());

    taskExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() {
        private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

        @Override/*from  ww w . ja  va 2s .c  o  m*/
        public Thread newThread(final Runnable r) {
            final Thread thread = defaultFactory.newThread(r);
            thread.setName("Http Site-to-Site PeerSelector");
            thread.setDaemon(true);
            return thread;
        }
    });

    taskExecutor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            peerSelector.refreshPeers();
        }
    }, 0, 5, TimeUnit.SECONDS);

}