List of usage examples for java.lang Thread setPriority
public final void setPriority(int newPriority)
From source file:com.petpet.c3po.controller.Controller.java
/** * Starts all the workers. Including the adaptors, consolidators and gatherer. * * @param collection//from w w w . j a v a 2 s .c o m * the name of the collection that is processed. * @param adaptThreads * the number of adaptor threads in the pool. * @param consThreads * the number of consolidator threads in the pool. * @param type * the type of the adaptors. * @param adaptorcnf * the adaptor configuration. */ private void startWorkers(String collection, int adaptThreads, int consThreads, String type, Map<String, String> adaptorcnf) { this.adaptorPool = Executors.newFixedThreadPool(adaptThreads); this.consolidatorPool = Executors.newFixedThreadPool(consThreads); List<Consolidator> consolidators = new ArrayList<Consolidator>(); LOG.debug("Initializing consolidators..."); for (int i = 0; i < consThreads; i++) { Consolidator c = new Consolidator(this.persistence, this.processingQueue); consolidators.add(c); this.consolidatorPool.submit(c); } // no more consolidators can be added. this.consolidatorPool.shutdown(); List<ProcessingRule> rules = this.getRules(collection); Collections.sort(rules, new Comparator<ProcessingRule>() { // sorts from descending @Override public int compare(ProcessingRule r1, ProcessingRule r2) { int first = this.fixPriority(r2.getPriority()); int second = this.fixPriority(r1.getPriority()); return new Integer(first).compareTo(new Integer(second)); } private int fixPriority(int prio) { if (prio < 0) return 0; if (prio > 1000) return 1000; return prio; } }); LOG.debug("Initializing adaptors..."); for (int i = 0; i < adaptThreads; i++) { AbstractAdaptor a = this.getAdaptor(type); a.setCache(this.persistence.getCache()); a.setQueue(this.processingQueue); a.setGatherer(this.gatherer); a.setConfig(adaptorcnf); a.setRules(rules); a.configure(); this.adaptorPool.submit(a); } // no more adaptors can be added. this.adaptorPool.shutdown(); Thread gathererThread = new Thread(this.gatherer, "MetadataGatherer"); gathererThread.setPriority(Thread.NORM_PRIORITY + 1); gathererThread.start(); try { // kills the pool and all adaptor workers after a month; boolean adaptorsTerminated = this.adaptorPool.awaitTermination(2678400, TimeUnit.SECONDS); if (adaptorsTerminated) { this.stopConsoldators(consolidators); this.consolidatorPool.awaitTermination(2678400, TimeUnit.SECONDS); } else { System.out.println("Oh my, It seems something went wrong. This process took too long"); LOG.error("Time out occurred, process was terminated"); } } catch (InterruptedException e) { LOG.error("An error occurred: {}", e.getMessage()); } finally { String path = FileUtils.getTempDirectory().getPath() + File.separator + "c3poarchives"; FileUtils.deleteQuietly(new File(path)); } // allow every rule to execute its tasks after job handling is done, like // printing statistics or cleaning up for (ProcessingRule processingRule : rules) { processingRule.onCommandFinished(); } ActionLog log = new ActionLog(collection, ActionLog.UPDATED_ACTION); new ActionLogHelper(this.persistence).recordAction(log); }
From source file:org.batoo.jpa.benchmark.BenchmarkTest.java
private ThreadPoolExecutor createExecutor(BlockingQueue<Runnable> workQueue) { final AtomicInteger nextThreadNo = new AtomicInteger(0); final ThreadPoolExecutor executor = new ThreadPoolExecutor(// BenchmarkTest.THREAD_COUNT, BenchmarkTest.THREAD_COUNT, // min max threads 0L, TimeUnit.MILLISECONDS, // the keep alive time - hold it forever workQueue, new ThreadFactory() { @Override// w w w .j a va 2s . c o m public Thread newThread(Runnable r) { final Thread t = new Thread(r); t.setDaemon(true); t.setPriority(Thread.NORM_PRIORITY); t.setName("Benchmark-" + nextThreadNo.get()); BenchmarkTest.this.threadIds[nextThreadNo.getAndIncrement()] = t.getId(); return t; } }); executor.prestartAllCoreThreads(); return executor; }
From source file:net.xmind.workbench.internal.notification.SiteEventNotificationService.java
private void showNotifications(final List<ISiteEvent> events) { if (workbench == null) return;/*from w ww.jav a 2 s. c om*/ if (canShowNotifications()) { doShowNotifications(events); } else { Thread thread = new Thread(new Runnable() { public void run() { while (!canShowNotifications()) { try { Thread.sleep(5000); } catch (InterruptedException e) { return; } } doShowNotifications(events); } }); thread.setPriority(Thread.MIN_PRIORITY); thread.setDaemon(true); thread.setName("WaitToShowNotifications"); //$NON-NLS-1$ thread.start(); } }
From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java
private int refreshFeeds(final long keepDateBorderTime) { ContentResolver cr = getContentResolver(); final Cursor cursor = cr.query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID, null, null, null); int nbFeed = (cursor != null) ? cursor.getCount() : 0; ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUMBER, new ThreadFactory() { @Override/*from www. j a v a2s. c om*/ public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } }); CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor); while (cursor != null && cursor.moveToNext()) { final String feedId = cursor.getString(0); completionService.submit(new Callable<Integer>() { @Override public Integer call() { int result = 0; try { result = refreshFeed(feedId, keepDateBorderTime); } catch (Exception e) { Log.e(TAG, "Error refreshing feed " + e.getMessage()); } return result; } }); } if (cursor != null) cursor.close(); int globalResult = 0; for (int i = 0; i < nbFeed; i++) { try { Future<Integer> f = completionService.take(); // ModPrivacyVandaag: the count of new articles after a feed is refreshed globalResult += f.get(); } catch (Exception e) { Log.e(TAG, "Error counting new articles " + e.getMessage()); } } executor.shutdownNow(); // To purge all threads return globalResult; // ModPrivacyVandaag: As far as I can see: this contains the number of new articles from a refresh of the feeds. }
From source file:org.openstreetmap.josm.tools.Utils.java
/** * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}. * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)} * @return a new {@link ThreadFactory}// w w w .j a va 2 s.c o m */ public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) { return new ThreadFactory() { final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(final Runnable runnable) { final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); thread.setPriority(threadPriority); return thread; } }; }
From source file:tvbrowser.TVBrowser.java
private static void startPeriodicSaveSettings() { // Every 5 minutes we store all the settings so they are stored in case of // an unexpected failure Thread saveThread = new Thread("Store settings periodically") { public void run() { mSaveThreadShouldStop = false; while (!mSaveThreadShouldStop) { try { Thread.sleep(5 * 60 * 1000); } catch (Exception exc) { // ignore }/*w ww. j a v a 2s.co m*/ if (!mSaveThreadShouldStop && !TvDataUpdater.getInstance().isDownloading()) { flushSettings(true); } } } }; saveThread.setPriority(Thread.MIN_PRIORITY); saveThread.start(); }
From source file:com.tealeaf.NativeShim.java
public void sendXHR(int id, String method, String url, String data, boolean async, String[] requestHeaders) { HashMap<String, String> requestHeadersMap = new HashMap<String, String>(); if (requestHeaders != null) { for (int i = 0; i < requestHeaders.length / 2; i++) { requestHeadersMap.put(requestHeaders[i * 2], requestHeaders[i * 2 + 1]); }//from w w w. j a v a 2s . c o m } XMLHttpRequest xhr = new XMLHttpRequest(id, method, url, data, async, requestHeadersMap); if (async) { Thread xhrThread = new Thread(xhr); xhrThread.setPriority(Thread.MIN_PRIORITY + 2); xhrThread.start(); } else { xhr.run(); } }
From source file:org.batoo.jpa.benchmark.BenchmarkTest.java
/** * // ww w.j av a 2s . c om * @since 2.0.0 */ @Before public void measureBefore() { this.profilingQueue = Lists.newArrayList(); final Thread t = new Thread(new Runnable() { @Override public void run() { BenchmarkTest.this.measureTimes(BenchmarkTest.this.profilingQueue); } }, "Profiler"); t.setDaemon(true); t.setPriority(Thread.MAX_PRIORITY); t.start(); }
From source file:gate.corpora.twitter.Population.java
@Override protected List<Action> buildActions(final NameBearerHandle handle) { List<Action> actions = new ArrayList<Action>(); if (!(handle.getTarget() instanceof Corpus)) return actions; actions.add(new AbstractAction("Populate from Twitter JSON files") { private static final long serialVersionUID = -8511779592856786327L; @Override//from w ww . j av a 2 s . com public void actionPerformed(ActionEvent e) { final PopulationDialogWrapper dialog = new PopulationDialogWrapper(); // If no files were selected then just stop try { final List<URL> fileUrls = dialog.getFileUrls(); if ((fileUrls == null) || fileUrls.isEmpty()) { return; } // Run the population in a separate thread so we don't lock up the GUI Thread thread = new Thread(Thread.currentThread().getThreadGroup(), "Twitter JSON Corpus Populator") { public void run() { try { for (URL fileUrl : fileUrls) { populateCorpus((Corpus) handle.getTarget(), fileUrl, dialog.getEncoding(), dialog.getContentKeys(), dialog.getFeatureKeys(), dialog.getTweetsPerDoc()); } } catch (ResourceInstantiationException e) { e.printStackTrace(); } } }; thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } catch (MalformedURLException e0) { e0.printStackTrace(); } } }); return actions; }
From source file:self.philbrown.droidQuery.Ajax.java
/** * Constructor//from ww w. j ava 2s .c o m * @param options used to configure this task */ public Ajax(AjaxOptions options) { this.options = options; if (options.url() == null) { throw new NullPointerException("Cannot call Ajax with null URL!"); } this.mHandler = new Handler(); this.executor = Executors.newFixedThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread t = new Thread(runnable); t.setPriority(Ajax.this.options.priority()); return t; } }); }