Example usage for java.lang Thread getPriority

List of usage examples for java.lang Thread getPriority

Introduction

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

Prototype

public final int getPriority() 

Source Link

Document

Returns this thread's priority.

Usage

From source file:Main.java

/**
 * Print a stack trace of the current thread.
 */// w  w w.  jav a 2 s  .c o  m
public static void printFullStackTrace() {
    Thread thread = Thread.currentThread();
    System.out.printf("  Thread id: %d, name: %s, state: %s, daemon: %s, EDT: %s\n", thread.getId(),
            thread.getName(), thread.getState(), thread.isDaemon(), EventQueue.isDispatchThread());
    ThreadGroup group = thread.getThreadGroup();
    System.out.printf("    priority: %d, group: %s, group count: %d\n", thread.getPriority(), group.getName(),
            group.activeCount());
    StackTraceElement[] backtrace = thread.getStackTrace();

    for (StackTraceElement e : backtrace) {
        System.out.printf("    Stack Trace: %s\n", e);
    }
}

From source file:Main.java

/**
 * Print diagnostic info about the current thread.
 *//*from   www . j  av a2 s  .com*/
public static void printThreadInfo() {
    Thread thread = Thread.currentThread();
    System.out.printf("  Thread id: %d, name: %s, state: %s, daemon: %s, EDT: %s\n", thread.getId(),
            thread.getName(), thread.getState(), thread.isDaemon(), EventQueue.isDispatchThread());
    ThreadGroup group = thread.getThreadGroup();
    System.out.printf("    priority: %d, group: %s, group count: %d\n", thread.getPriority(), group.getName(),
            group.activeCount());
    StackTraceElement[] backtrace = thread.getStackTrace();
    if (backtrace.length > 2) {
        System.out.printf("    trace[2]: %s\n", backtrace[2]);
    }
}

From source file:com.ery.estorm.util.Threads.java

/**
 * Get a named {@link ThreadFactory} that just builds daemon threads.
 * //from  ww  w  .  j a v  a  2 s  . c  om
 * @param prefix
 *            name prefix for all threads created from the factory
 * @param handler
 *            unhandles exception handler to set for all threads
 * @return a thread factory that creates named, daemon threads with the supplied exception handler and normal priority
 */
public static ThreadFactory newDaemonThreadFactory(final String prefix,
        final UncaughtExceptionHandler handler) {
    final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (handler != null) {
                t.setUncaughtExceptionHandler(handler);
            }
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }

    };
}

From source file:ThreadViewer.java

private void createPendingCellData() {
    Thread[] thread = findAllThreads();
    Object[][] cell = new Object[thread.length][columnCount];

    for (int i = 0; i < thread.length; i++) {
        Thread t = thread[i];
        Object[] rowCell = cell[i];

        rowCell[0] = new Integer(t.getPriority());
        rowCell[1] = new Boolean(t.isAlive());
        rowCell[2] = new Boolean(t.isDaemon());
        rowCell[3] = new Boolean(t.isInterrupted());
        rowCell[4] = t.getThreadGroup().getName();
        rowCell[5] = t.getName();/*from w ww .  j ava 2s  .  c o m*/
    }

    synchronized (dataLock) {
        pendingCellData = cell;
    }
}

From source file:net.pms.util.BasicThreadFactory.java

@Override
public Thread newThread(Runnable runnable) {
    String threadName;/*from  w  ww .j a  va 2  s  .co  m*/
    switch (numVariables) {
    case 0:
        threadName = namePattern;
        break;
    case 1:
        threadName = String.format(Locale.ROOT, namePattern, threadNumber.getAndIncrement());
        break;
    default:
        threadName = String.format(Locale.ROOT, namePattern, instancePoolNumber,
                threadNumber.getAndIncrement());
    }
    Thread thread = new Thread(group, runnable, threadName, 0);
    if (thread.isDaemon()) {
        thread.setDaemon(false);
    }
    if (thread.getPriority() != threadPriority) {
        thread.setPriority(threadPriority);
    }
    return thread;
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

/**
 * returns workersExecutorService.//from w  ww  .  ja  v a 2s  .co 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 w ww .  ja  v  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.alibaba.wasp.master.AssignmentManager.java

/**
 * Get a named {@link java.util.concurrent.ThreadFactory} that just builds daemon threads
 *
 * @param prefix//  w  w  w . j  a v a  2s . com
 *          name prefix for all threads created from the factory
 * @return a thread factory that creates named, daemon threads
 */
private static ThreadFactory newDaemonThreadFactory(final String prefix) {
    final ThreadFactory namedFactory = Threads.getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    };
}

From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java

/**
 * Constructs MarketplaceWebServiceClient with AWS Access Key ID, AWS Secret Key
 * and MarketplaceWebServiceConfig. Use MarketplaceWebServiceConfig to pass additional
 * configuration that affects how service is being called.
 *
 * @param awsAccessKeyId/*from   www  .j a v  a2s  . c o m*/
 *          AWS Access Key ID
 * @param awsSecretAccessKey
 *          AWS Secret Access Key
 * @param config
 *          Additional configuration options
 */
@SuppressWarnings("serial")
public MarketplaceWebServiceClient(String awsAccessKeyId, String awsSecretAccessKey, String applicationName,
        String applicationVersion, MarketplaceWebServiceConfig config) {
    this.awsAccessKeyId = awsAccessKeyId;
    this.awsSecretAccessKey = awsSecretAccessKey;
    this.config = config;
    this.httpClient = configureHttpClient(applicationName, applicationVersion);
    this.asyncExecutor = new ThreadPoolExecutor(config.getMaxAsyncThreads(), config.getMaxAsyncThreads(), 60L,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(config.getMaxAsyncQueueSize()) {

                @Override
                public boolean offer(Runnable task) {
                    log.debug("Maximum number of concurrent threads reached, queuing task...");
                    return super.offer(task);
                }
            }, new ThreadFactory() {

                private final AtomicInteger threadNumber = new AtomicInteger(1);

                public Thread newThread(Runnable task) {
                    Thread thread = new Thread(task,
                            "MarketplaceWebServiceClient-Thread-" + threadNumber.getAndIncrement());
                    thread.setDaemon(true);
                    if (thread.getPriority() != Thread.NORM_PRIORITY) {
                        thread.setPriority(Thread.NORM_PRIORITY);
                    }
                    log.debug("ThreadFactory created new thread: " + thread.getName());
                    return thread;
                }
            }, new RejectedExecutionHandler() {

                public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                    log.debug("Maximum number of concurrent threads reached, and queue is full. "
                            + "Running task in the calling thread..." + Thread.currentThread().getName());
                    if (!executor.isShutdown()) {
                        task.run();
                    }
                }
            });
}