Example usage for java.lang Thread setPriority

List of usage examples for java.lang Thread setPriority

Introduction

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

Prototype

public final void setPriority(int newPriority) 

Source Link

Document

Changes the priority of this thread.

Usage

From source file:tvbrowser.extras.reminderplugin.ReminderSettingsTab.java

/**
 * Called by the host-application, if the user wants to save the settings.
 *///from  w ww  . j  a  v  a 2s.c o  m
public void saveSettings() {
    mSettings.setProperty("soundfile", mSoundFileChB.getTextField().getText());
    mSettings.setProperty("execfile", mExecFileStr);
    mSettings.setProperty("execparam", mExecParamStr);

    mSettings.setProperty("usemsgbox", String.valueOf(mReminderWindowChB.isSelected()));
    mSettings.setProperty("usesound", String.valueOf(mSoundFileChB.isSelected()));
    mSettings.setProperty("usebeep", String.valueOf(mBeep.isSelected()));
    mSettings.setProperty("useexec", String.valueOf(mExecChB.isSelected()));

    ReminderPlugin.getInstance().setClientPluginsTargets(mClientPluginTargets);

    mSettings.setProperty("autoCloseBehaviour",
            mCloseOnEnd.isSelected() ? "onEnd" : mCloseNever.isSelected() ? "never" : "onTime");

    mSettings.setProperty("autoCloseReminderTime", mAutoCloseReminderTimeSp.getValue().toString());
    mSettings.setProperty("defaultReminderEntry",
            Integer.toString(mDefaultReminderEntryList.getSelectedIndex()));
    mSettings.setProperty("showTimeSelectionDialog", String.valueOf(mShowTimeSelectionDlg.isSelected()));
    mSettings.setProperty("showRemovedDialog", String.valueOf(mShowRemovedDlg.isSelected()));

    mSettings.setProperty("showTimeCounter",
            String.valueOf(!mCloseNever.isSelected() && mShowTimeCounter.isSelected()));
    mSettings.setProperty("alwaysOnTop", String.valueOf(mShowAlwaysOnTop.isSelected()));

    ReminderPlugin.getInstance().setMarkPriority(mMarkingsPanel.getSelectedPriority());

    Thread saveThread = new Thread("Save reminders") {
        public void run() {
            ReminderPlugin.getInstance().store();
        }
    };
    saveThread.setPriority(Thread.MIN_PRIORITY);
    saveThread.start();
}

From source file:com.xpn.xwiki.plugin.lucene.IndexRebuilder.java

public synchronized int startIndex(Collection<String> wikis, String hqlFilter, boolean clearIndex,
        boolean onlyNew, XWikiContext context) {
    if (this.rebuildInProgress) {
        LOGGER.warn("Cannot launch rebuild because another rebuild is in progress");

        return LucenePluginApi.REBUILD_IN_PROGRESS;
    } else {//from   w  ww. j  a v  a 2s.c  o  m
        if (clearIndex) {
            if (wikis == null) {
                this.indexUpdater.cleanIndex();
            } else {
                // TODO: clean wikis listed in wikis
            }
        }

        this.wikis = wikis != null ? new ArrayList<String>(wikis) : null;
        this.hqlFilter = hqlFilter;
        this.onlyNew = onlyNew;
        this.rebuildInProgress = true;

        Thread indexRebuilderThread = new Thread(this, "Lucene Index Rebuilder");
        // The JVM should be allowed to shutdown while this thread is running
        indexRebuilderThread.setDaemon(true);
        // Client requests are more important than indexing
        indexRebuilderThread.setPriority(3);
        // Finally, start the rebuild in the background
        indexRebuilderThread.start();

        // Too bad that now we can't tell how many items are there to be indexed...
        return 0;
    }
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Submits stats logs to the server. Spawns a separate thread to do all the
 * work so that we don't block the UI if the server doesn't respond.
 *///from w w  w  .j a  va 2s.co m
private void uploadLogs() {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            String oldLogSet = rotate();
            uploadLogs(oldLogSet);
        }
    };
    Thread t = new Thread(r);
    t.setName("SubmitLogs");
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:com.xpn.xwiki.plugin.lucene.internal.IndexRebuilder.java

public synchronized int startIndex(Collection<String> wikis, String hqlFilter, boolean clearIndex,
        boolean onlyNew, XWikiContext context) {
    if (this.rebuildInProgress) {
        LOGGER.warn("Cannot launch rebuild because another rebuild is in progress");

        return LucenePluginApi.REBUILD_IN_PROGRESS;
    } else {/* w  w w. ja  v a2s  .  c  om*/
        if (clearIndex) {
            if (wikis == null) {
                this.indexUpdater.cleanIndex();
            } else {
                try {
                    IndexWriter writer = this.indexUpdater.openWriter(false);
                    try {
                        for (String wiki : wikis) {
                            writer.deleteDocuments(new Term(IndexFields.DOCUMENT_WIKI, wiki));
                        }
                    } finally {
                        writer.close();
                    }
                } catch (IOException ex) {
                    LOGGER.warn("Failed to clean wiki index: {}", ex.getMessage());
                }
            }
        }

        this.wikis = wikis != null ? new ArrayList<String>(wikis) : null;
        this.hqlFilter = hqlFilter;
        this.onlyNew = onlyNew;
        this.rebuildInProgress = true;

        Thread indexRebuilderThread = new Thread(this, "Lucene Index Rebuilder");
        // The JVM should be allowed to shutdown while this thread is running
        indexRebuilderThread.setDaemon(true);
        // Client requests are more important than indexing
        indexRebuilderThread.setPriority(3);
        // Finally, start the rebuild in the background
        indexRebuilderThread.start();

        // Too bad that now we can't tell how many items are there to be indexed...
        return 0;
    }
}

From source file:net.sf.golly.HelpActivity.java

private String DownloadFile(String urlstring, String filepath) {
    // we cannot do network connections on main thread, so we do the
    // download on a new thread, but we have to wait for it to finish
    final Handler handler = new LooperInterrupter();

    cancelled = false;//ww w.j  ava2  s  . c om
    progbar.setProgress(0);
    // don't show proglayout immediately
    // proglayout.setVisibility(LinearLayout.VISIBLE);

    dresult = "";
    final String durl = urlstring;
    final String dfile = filepath;
    Thread download_thread = new Thread(new Runnable() {
        public void run() {
            dresult = downloadURL(durl, dfile);
            handler.sendMessage(handler.obtainMessage());
        }
    });

    download_thread.setPriority(Thread.MAX_PRIORITY);
    download_thread.start();

    // wait for thread to finish
    try {
        Looper.loop();
    } catch (RuntimeException re) {
    }

    proglayout.setVisibility(LinearLayout.INVISIBLE);

    if (dresult.length() > 0 && !cancelled) {
        Toast.makeText(this, "Download failed! " + dresult, Toast.LENGTH_SHORT).show();
    }
    return dresult;
}

From source file:org.eclipse.scanning.event.SubscriberImpl.java

private void schedule(DiseminateEvent event) {
    if (isSynchronous()) {
        if (queue != null)
            queue.add(event);/* w ww  .j  av  a 2 s .  co m*/
    } else {
        if (event == DiseminateEvent.STOP)
            return;
        // TODO FIXME Might not be right...
        final Thread thread = new Thread("Execute event " + getTopicName()) {
            public void run() {
                diseminate(event); // Use this JMS thread directly to do work.
            }
        };
        thread.setDaemon(true);
        thread.setPriority(Thread.NORM_PRIORITY + 1);
        thread.start();
    }
}

From source file:org.polymap.core.runtime.PolymapThreadPoolExecutor.java

public static PolymapThreadPoolExecutor newInstance() {
    // policy:/*w w  w  . j  av a 2s. c  o  m*/
    //   - first: spawn up to proc*6 threads (stopped when idle for 180s)
    //   - then: queue 3 times more jobs (for faster feeding workers)
    //   - then: block until queue can take another job
    //   - and/or: expand corePoolSize (via bounds checkecker thread)
    int procs = Runtime.getRuntime().availableProcessors();
    final int nThreads = procs * 6;
    final int maxThreads = nThreads * 5;

    // Proper queue bound semantics but just half the task througput of
    // LinkedBlockingQueue in PerfTest
    // BlockingQueue queue = new ArrayBlockingQueue( nThreads * 5 );

    // Fastest. But unfortunatelle does not limit the number of queued
    // task, which might result in OOM or similar problem.
    final LinkedBlockingQueue queue = new LinkedBlockingQueue( /*nThreads * 3*/ );

    // Slowest queue. Does not feed the workers well if pool size exeeds.
    // BlockingQueue queue = new SynchronousQueue();

    final PolymapThreadPoolExecutor result = new PolymapThreadPoolExecutor(nThreads, maxThreads, 3 * 60, queue);
    result.allowCoreThreadTimeOut(true);

    // async queue bounds checker for unbound LinkedQueue
    Thread boundsChecker = new Thread("ThreadPoolBoundsChecker") {
        public void run() {
            int bound = result.getCorePoolSize() * 3;
            while (queue != null) {
                try {
                    Thread.sleep(1000);
                    //                        log.info( "queued:" + queue.size() 
                    //                                + " - pool:" + result.getCorePoolSize() 
                    //                                + " - largest:" + result.getLargestPoolSize() 
                    //                                + " - completed:" + result.getCompletedTaskCount() );
                    // need more threads?
                    if (queue.size() > bound && result.getCorePoolSize() < maxThreads) {
                        int n = result.getCorePoolSize() + nThreads;
                        log.info("Thread Pool: increasing core pool size to: " + n);
                        result.setCorePoolSize(n);
                    }
                    // shrink down?
                    if (queue.isEmpty() && result.getActiveCount() == 0
                            && result.getCorePoolSize() > nThreads) {
                        log.info("Thread Pool: decreasing core pool size to: " + nThreads);
                        result.setCorePoolSize(nThreads);
                    }
                } catch (Throwable e) {
                    log.warn("", e);
                }
            }
        }
    };
    boundsChecker.setPriority(Thread.MIN_PRIORITY);
    boundsChecker.start();

    return result;
}

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

/**
 * returns workersExecutorService./*from   w w  w .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: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 w w .  j av a2 s . com
        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.baidu.asynchttpclient.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from   w w  w. j  a  v a  2s .c om
 */
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>();
}