Example usage for java.lang Thread isDaemon

List of usage examples for java.lang Thread isDaemon

Introduction

In this page you can find the example usage for java.lang Thread isDaemon.

Prototype

public final boolean isDaemon() 

Source Link

Document

Tests if this thread is a daemon thread.

Usage

From source file:org.openflamingo.remote.thrift.thriftfs.ThriftHandlerBase.java

/**
 * Return a list of threads that currently exist with their stack traces
 *///from   w  w  w  .  j  a  v  a 2  s.  c  o  m
public List<ThreadStackTrace> getThreadDump(RequestContext ctx) {
    List<ThreadStackTrace> dump = new ArrayList<ThreadStackTrace>();

    Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) {
        final Thread t = entry.getKey();
        final StackTraceElement[] frames = entry.getValue();

        ThreadStackTrace tst = new ThreadStackTrace();
        tst.threadName = t.getName();
        tst.threadStringRepresentation = String.valueOf(t);
        tst.isDaemon = t.isDaemon();
        tst.stackTrace = new ArrayList<StackTraceElement>();
        for (StackTraceElement ste : frames) {
            StackTraceElement tFrame = new StackTraceElement();
            tFrame.className = ste.getClassName();
            tFrame.fileName = ste.getFileName();
            tFrame.lineNumber = ste.getLineNumber();
            tFrame.methodName = ste.getMethodName();
            tFrame.isNativeMethod = ste.isNativeMethod();
            tFrame.stringRepresentation = String.valueOf(ste);
            tst.stackTrace.add(tFrame);
        }
        dump.add(tst);
    }
    return dump;
}

From source file:org.apache.hadoop.thriftfs.ThriftHandlerBase.java

/**
 * Return a list of threads that currently exist with their stack traces
 *///  w w  w  .j a  v  a2s . c  om
public List<ThreadStackTrace> getThreadDump(RequestContext ctx) {
    List<ThreadStackTrace> dump = new ArrayList<ThreadStackTrace>();

    Map<Thread, java.lang.StackTraceElement[]> traces = Thread.getAllStackTraces();
    for (Map.Entry<Thread, java.lang.StackTraceElement[]> entry : traces.entrySet()) {
        final Thread t = entry.getKey();
        final java.lang.StackTraceElement[] frames = entry.getValue();

        ThreadStackTrace tst = new ThreadStackTrace();
        tst.threadName = t.getName();
        tst.threadStringRepresentation = String.valueOf(t);
        tst.isDaemon = t.isDaemon();
        tst.stackTrace = new ArrayList<StackTraceElement>();
        for (java.lang.StackTraceElement ste : frames) {
            StackTraceElement tFrame = new StackTraceElement();
            tFrame.className = ste.getClassName();
            tFrame.fileName = ste.getFileName();
            tFrame.lineNumber = ste.getLineNumber();
            tFrame.methodName = ste.getMethodName();
            tFrame.isNativeMethod = ste.isNativeMethod();
            tFrame.stringRepresentation = String.valueOf(ste);
            tst.stackTrace.add(tFrame);
        }
        dump.add(tst);
    }
    return dump;
}

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 w ww  .  j a v  a 2 s.  c om
        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:org.jdesktop.swingworker.AccumulativeRunnable.java

/**
 * returns workersExecutorService.//from www  . j a v a 2  s . c  o  m
 *
 * returns the service stored in the appContext or creates it if
 * necessary. If the last one it triggers autoShutdown thread to
 * get started.
 * 
 * @return ExecutorService for the {@code SwingWorkers}
 * @see #startAutoShutdownThread
 */
private static synchronized ExecutorService getWorkersExecutorService() {
    if (executorService == null) {
        //this creates non-daemon threads. 
        ThreadFactory threadFactory = 
            new ThreadFactory() {
                final AtomicInteger threadNumber = new AtomicInteger(1);
                public Thread newThread(final Runnable r) {
                    StringBuilder name = 
                        new StringBuilder("SwingWorker-pool-");
                    name.append(System.identityHashCode(this));
                    name.append("-thread-");
                    name.append(threadNumber.getAndIncrement());
                             
                    Thread t = new Thread(r, name.toString());;
                    if (t.isDaemon())
                        t.setDaemon(false);
                    if (t.getPriority() != Thread.NORM_PRIORITY)
                        t.setPriority(Thread.NORM_PRIORITY);
                    return t;
                }
            };

        /*
         * We want a to have no more than MAX_WORKER_THREADS
         * running threads.
         *
         * We want a worker thread to wait no longer than 1 second
         * for new tasks before terminating.
         */
        executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS,
                                     5L, TimeUnit.SECONDS,
                                     new LinkedBlockingQueue<Runnable>(),
                                     threadFactory) {

                private final ReentrantLock pauseLock = new ReentrantLock();
                private final Condition unpaused = pauseLock.newCondition();
                private boolean isPaused = false;
                private final ReentrantLock executeLock = new ReentrantLock();
                    
                @Override
                public void execute(Runnable command) {
                    /*
                     * ThreadPoolExecutor first tries to run task
                     * in a corePool. If all threads are busy it
                     * tries to add task to the waiting queue. If it
                     * fails it run task in maximumPool.
                     *
                     * We want corePool to be 0 and
                     * maximumPool to be MAX_WORKER_THREADS
                     * We need to change the order of the execution.
                     * First try corePool then try maximumPool
                     * pool and only then store to the waiting
                     * queue. We can not do that because we would
                     * need access to the private methods.
                     *
                     * Instead we enlarge corePool to
                     * MAX_WORKER_THREADS before the execution and
                     * shrink it back to 0 after. 
                     * It does pretty much what we need.
                     *
                     * While we changing the corePoolSize we need
                     * to stop running worker threads from accepting new
                     * tasks.
                     */
                        
                    //we need atomicity for the execute method.
                    executeLock.lock();
                    try {

                        pauseLock.lock();
                        try {
                            isPaused = true;
                        } finally {
                            pauseLock.unlock();
                        }
                            
                        setCorePoolSize(MAX_WORKER_THREADS);
                        super.execute(command);
                        setCorePoolSize(0);
                            
                        pauseLock.lock();
                        try {
                            isPaused = false;
                            unpaused.signalAll();
                        } finally {
                            pauseLock.unlock();
                        }
                    } finally {
                        executeLock.unlock();
                    }
                }
                @Override 
                protected void afterExecute(Runnable r, Throwable t) { 
                    super.afterExecute(r, t);
                    pauseLock.lock();
                    try {
                        while(isPaused) {
                            unpaused.await();
                        }
                    } catch(InterruptedException ignore) {
                            
                    } finally {
                        pauseLock.unlock();
                    }
                }
            };
    }
    return executorService; 
}

From source file:com.baidu.asynchttpclient.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from  ww w .  jav a 2  s . c  o  m
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {

            Thread t = new Thread(r, "AsyncHttpClient #" + mCount.getAndIncrement());
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != (Thread.NORM_PRIORITY - 1))
                t.setPriority((Thread.NORM_PRIORITY - 1));
            return t;
        }
    });

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

private void joinNonDaemonThreads(ThreadGroup threadGroup) {
    boolean foundNonDaemon;
    do {/* www  .j  a  va2  s . c  om*/
        foundNonDaemon = false;
        Collection<Thread> threads = getActiveThreads(threadGroup);
        for (Thread thread : threads) {
            if (thread.isDaemon()) {
                continue;
            }
            foundNonDaemon = true; // try again; maybe more threads were created while we were busy
            joinThread(thread, 0);
        }
    } while (foundNonDaemon);
}

From source file:org.elasticsearch.client.sniff.SnifferTests.java

public void testDefaultSchedulerThreadFactory() {
    DefaultScheduler defaultScheduler = new DefaultScheduler();
    try {//  www  .j av  a 2s .c o  m
        ScheduledExecutorService executorService = defaultScheduler.executor;
        assertThat(executorService, instanceOf(ScheduledThreadPoolExecutor.class));
        assertThat(executorService, instanceOf(ScheduledThreadPoolExecutor.class));
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) executorService;
        assertTrue(executor.getRemoveOnCancelPolicy());
        assertFalse(executor.getContinueExistingPeriodicTasksAfterShutdownPolicy());
        assertTrue(executor.getExecuteExistingDelayedTasksAfterShutdownPolicy());
        assertThat(executor.getThreadFactory(), instanceOf(Sniffer.SnifferThreadFactory.class));
        int iters = randomIntBetween(3, 10);
        for (int i = 1; i <= iters; i++) {
            Thread thread = executor.getThreadFactory().newThread(new Runnable() {
                @Override
                public void run() {

                }
            });
            assertThat(thread.getName(), equalTo("es_rest_client_sniffer[T#" + i + "]"));
            assertThat(thread.isDaemon(), is(true));
        }
    } finally {
        defaultScheduler.shutdown();
    }
}

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

protected IDataToRouteReader startReading(ChannelRouterContext context) {
    IDataToRouteReader reader = new DataGapRouteReader(context, engine);
    if (parameterService.is(ParameterConstants.SYNCHRONIZE_ALL_JOBS)) {
        reader.run();//from w w  w  . j  a  v  a 2 s.  co m
    } else {
        if (readThread == null) {
            readThread = Executors.newCachedThreadPool(new ThreadFactory() {
                final AtomicInteger threadNumber = new AtomicInteger(1);
                final String namePrefix = parameterService.getEngineName().toLowerCase() + "-router-reader-";

                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;
                }
            });
        }
        readThread.execute(reader);
    }

    return reader;
}

From source file:com.gargoylesoftware.htmlunit.javascript.JavaScriptEngineTest.java

/**
 * Ensures that the JS executor thread is a daemon thread.
 * @throws Exception if the test fails// w ww .ja va 2  s.  c  o  m
 */
@Test
public void daemonExecutorThread() throws Exception {
    final String html = "<html><body><script>\n" + "function f() { alert('foo'); }\n" + "setTimeout(f, 5);\n"
            + "</script>\n" + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<String>();
    final HtmlPage page = loadPage(getBrowserVersion(), html, collectedAlerts);

    Thread.sleep(20);
    final List<Thread> jsThreads = getJavaScriptThreads();
    assertEquals(1, jsThreads.size());
    final Thread jsThread = jsThreads.get(0);
    assertEquals("JS executor for " + page.getWebClient(), jsThread.getName());
    assertTrue(jsThread.isDaemon());
}

From source file:com.spotify.helios.system.SystemTestBase.java

private void listThreads() {
    final Set<Thread> threads = Thread.getAllStackTraces().keySet();
    final Map<String, Thread> sorted = Maps.newTreeMap();
    for (final Thread t : threads) {
        final ThreadGroup tg = t.getThreadGroup();
        if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) {
            sorted.put(t.getName(), t);
        }/*www .  j  a v a 2  s.  co m*/
    }
    log.info("= THREADS " + Strings.repeat("=", 70));
    for (final Thread t : sorted.values()) {
        final ThreadGroup tg = t.getThreadGroup();
        log.info("{}: \"{}\" ({}{})", t.getId(), t.getName(), (tg == null ? "" : tg.getName() + " "),
                (t.isDaemon() ? "daemon" : ""));
    }
    log.info(Strings.repeat("=", 80));
}