List of usage examples for java.lang Thread NORM_PRIORITY
int NORM_PRIORITY
To view the source code for java.lang Thread NORM_PRIORITY.
Click Source Link
From source file:free.yhc.feeder.model.Utils.java
/** * Get BG task thread priority from shared preference. * @param context/*from w w w. j a v a2 s . c o m*/ * @return * Value of Java Thread priority (between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY) */ public static int getPrefBGTaskPriority() { String prio = sPrefs.getString(getResString(R.string.csbgtask_prio), getResString(R.string.cslow)); if (getResString(R.string.cslow).equals(prio)) return Thread.MIN_PRIORITY; else if (getResString(R.string.csmedium).equals(prio)) return (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2; else if (getResString(R.string.cshigh).equals(prio)) return Thread.NORM_PRIORITY; else { eAssert(false); return Thread.MIN_PRIORITY; } }
From source file:lenscorrection.Distortion_Correction.java
protected String correctImages() { if (!sp.applyCorrection) { sp.target_dir = System.getProperty("user.dir").replace('\\', '/') + "/distCorr_tmp/"; System.out.println("Tmp target directory: " + sp.target_dir); if (new File(sp.target_dir).exists()) { System.out.println("removing old tmp directory!"); final String[] filesToDelete = new File(sp.target_dir).list(); for (int i = 0; i < filesToDelete.length; i++) { System.out.println(filesToDelete[i]); final boolean deleted = new File(sp.target_dir + filesToDelete[i]).delete(); if (!deleted) IJ.log("Error: Could not remove temporary directory!"); }//from w w w .ja v a 2s. co m new File(sp.target_dir).delete(); } try { // Create one directory final boolean success = (new File(sp.target_dir)).mkdir(); if (success) new File(sp.target_dir).deleteOnExit(); } catch (final Exception e) { IJ.showMessage("Error! Could not create temporary directory. " + e.getMessage()); } } if (sp.target_dir == "" || null == sp.target_dir) { final DirectoryChooser dc = new DirectoryChooser("Target Directory"); sp.target_dir = dc.getDirectory(); if (null == sp.target_dir) return null; sp.target_dir = sp.target_dir.replace('\\', '/'); if (!sp.target_dir.endsWith("/")) sp.target_dir += "/"; } final String[] namesTarget = new File(sp.target_dir).list(new FilenameFilter() { @Override public boolean accept(final File dir, final String namesTarget) { final int idot = namesTarget.lastIndexOf('.'); if (-1 == idot) return false; return namesTarget.contains(namesTarget.substring(idot).toLowerCase()); } }); if (namesTarget.length > 0) IJ.showMessage("Overwrite Message", "There are already images in that directory. These will be used for evaluation."); else { IJ.showStatus("Correcting Images"); final Thread[] threads = MultiThreading.newThreads(); final AtomicInteger ai = new AtomicInteger(sp.applyCorrection ? 0 : sp.firstImageIndex); for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { @Override public void run() { setPriority(Thread.NORM_PRIORITY); for (int i = ai.getAndIncrement(); i < (sp.applyCorrection ? sp.names.length : (sp.firstImageIndex + sp.numberOfImages)); i = ai.getAndIncrement()) { IJ.log("Correcting image " + sp.names[i]); final ImagePlus imps = new Opener().openImage(sp.source_dir + sp.names[i]); imps.setProcessor(imps.getTitle(), imps.getProcessor().convertToShort(false)); final ImageProcessor[] transErg = nlt.transform(imps.getProcessor()); imps.setProcessor(imps.getTitle(), transErg[0]); if (!sp.applyCorrection) new File(sp.target_dir + sp.names[i]).deleteOnExit(); new FileSaver(imps).saveAsTiff(sp.target_dir + sp.names[i]); } } }; } MultiThreading.startAndJoin(threads); } return sp.target_dir; }
From source file:com.android.leanlauncher.LauncherModel.java
public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); }//from w w w .ja v a2 s. com // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. synchronized (mDeferredBindRunnables) { mDeferredBindRunnables.clear(); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } }
From source file:org.lockss.app.LockssDaemon.java
/** * Main entry to the daemon. Startup arguments: * * -p url1//from www. j a va 2 s . com * Load properties from url1 * -p url1 -p url2;url3;url4 * Load properties from url1 AND from one of * (url2 | url3 | url4) * -g group_name[;group_2;group_3] * Set the daemon groups. Multiple groups separated by semicolon. */ public static void main(String[] args) { LockssDaemon daemon; if (!SystemUtils.isJavaVersionAtLeast(MIN_JAVA_VERSION)) { System.err.println("LOCKSS requires at least Java " + MIN_JAVA_VERSION + ", this is " + SystemUtils.JAVA_VERSION + ", exiting."); System.exit(Constants.EXIT_CODE_JAVA_VERSION); } StartupOptions opts = getStartupOptions(args); setSystemProperties(); try { daemon = new LockssDaemon(opts.getPropUrls(), opts.getGroupNames()); daemon.startDaemon(); // raise priority after starting other threads, so we won't get // locked out and fail to exit when told. Thread.currentThread().setPriority(Thread.NORM_PRIORITY + 2); } catch (ResourceUnavailableException e) { log.error("Exiting because required resource is unavailable", e); System.exit(Constants.EXIT_CODE_RESOURCE_UNAVAILABLE); return; // compiler doesn't know that // System.exit() doesn't return } catch (Throwable e) { log.error("Exception thrown in main loop", e); System.exit(Constants.EXIT_CODE_EXCEPTION_IN_MAIN); return; // compiler doesn't know that // System.exit() doesn't return } if (CurrentConfig.getBooleanParam(PARAM_APP_EXIT_IMM, DEFAULT_APP_EXIT_IMM)) { try { daemon.stop(); } catch (RuntimeException e) { // ignore errors stopping daemon } System.exit(Constants.EXIT_CODE_NORMAL); } daemon.keepRunning(); log.info("Exiting because time to die"); System.exit(Constants.EXIT_CODE_NORMAL); }
From source file:axiom.framework.core.Application.java
/** * Create and start scheduler and cleanup thread *//*from w ww . ja va2s .c om*/ public void start() { starttime = System.currentTimeMillis(); this.onStart(); synchronized (this) { worker = new Thread(this, "Worker-" + name); worker.setPriority(Thread.NORM_PRIORITY + 1); worker.start(); } }
From source file:com.intuit.tank.harness.APITestHarness.java
/** * Run concurrent test plans at the same time * //from w ww.ja va 2s .com * @param parser */ public void runConcurrentTestPlans() { if (started) { LOG.warn("Agent already started. Ignoring start command"); return; } tpsMonitor = new TPSMonitor(tankConfig.getAgentConfig().getTPSPeriod()); StringBuilder info = new StringBuilder().append(" RAMP_TIME=").append(agentRunData.getRampTime()) .append("; agentRunData.getNumUsers()=").append(agentRunData.getNumUsers()) .append("; NUM_START_THREADS=").append(agentRunData.getNumStartUsers()).append("; simulationTime=") .append(agentRunData.getSimulationTime()); LOG.info(LogUtil.getLogMessage("starting test with " + info.toString())); started = true; if (agentRunData.getJobId() == null) { String jobId = AmazonUtil.getJobId(); agentRunData.setJobId(jobId); } TestPlanRunner[] sessions = new TestPlanRunner[agentRunData.getNumUsers()]; sessionThreads = new Thread[agentRunData.getNumUsers()]; Thread monitorThread = null; doneSignal = new CountDownLatch(agentRunData.getNumUsers()); try { HDWorkload hdWorkload = TestPlanSingleton.getInstance().getTestPlans().get(0); if (StringUtils.isBlank(tankHttpClientClass)) { tankHttpClientClass = hdWorkload.getTankHttpClientClass(); } agentRunData.setProjectName(hdWorkload.getName()); agentRunData.setTankhttpClientClass(tankHttpClientClass); List<TestPlanStarter> testPlans = new ArrayList<TestPlanStarter>(); int total = 0; for (HDTestPlan plan : hdWorkload.getPlans()) { if (plan.getUserPercentage() > 0) { plan.setVariables(hdWorkload.getVariables()); TestPlanStarter starter = new TestPlanStarter(plan, agentRunData.getNumUsers()); total += starter.getNumThreads(); testPlans.add(starter); LOG.info(LogUtil.getLogMessage("Users for Test Plan " + plan.getTestPlanName() + " at " + plan.getUserPercentage() + "% = " + starter.getNumThreads())); } } LOG.info(LogUtil.getLogMessage("Total Users calculated for all test Plans = " + total)); if (total != agentRunData.getNumUsers()) { int numToAdd = agentRunData.getNumUsers() - total; TestPlanStarter starter = testPlans.get(testPlans.size() - 1); LOG.info(LogUtil.getLogMessage( "adding " + numToAdd + " threads to testPlan " + starter.getPlan().getTestPlanName())); starter.setNumThreads(starter.getNumThreads() + numToAdd); } // create threads int tp = 0; for (TestPlanStarter starter : testPlans) { for (int i = 0; i < starter.getNumThreads(); i++) { sessions[tp] = new TestPlanRunner(starter.getPlan(), tp); sessionThreads[tp] = new Thread(threadGroup, sessions[tp], "AGENT"); sessionThreads[tp].setDaemon(true);// system won't shut down normally until all user threads stop starter.addThread(sessionThreads[tp]); sessions[tp].setUniqueName( sessionThreads[tp].getThreadGroup().getName() + "-" + sessionThreads[tp].getId()); tp++; } } LOG.info(LogUtil.getLogMessage("Have all testPlan runners configured")); // start status thread first only if (!isLocal && !isDebug() && NumberUtils.isDigits(agentRunData.getJobId())) { LOG.info(LogUtil.getLogMessage("Starting monitor thread...")); CloudVmStatus status = getInitialStatus(); monitorThread = new Thread(new APIMonitor(status)); monitorThread.setDaemon(true); monitorThread.setPriority(Thread.NORM_PRIORITY - 2); monitorThread.start(); } LOG.info(LogUtil.getLogMessage("Starting threads...")); // start initial users startTime = System.currentTimeMillis(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); LOG.info(LogUtil.getLogMessage("Simulation start: " + df.format(new Date(getStartTime())))); if (agentRunData.getSimulationTime() != 0) { LOG.info(LogUtil.getLogMessage( "Scheduled Simulation End : " + df.format(new Date(getSimulationEndTimeMillis())))); LOG.info(LogUtil.getLogMessage( "Max Simulation End : " + df.format(new Date(getMaxSimulationEndTimeMillis())))); } else { LOG.info(LogUtil.getLogMessage("Ends at script loops completed with no Max Simulation Time.")); } currentNumThreads = 0; if (agentRunData.getNumUsers() > 0) { for (TestPlanStarter starter : testPlans) { if (isDebug()) { starter.run(); } else { Thread t = new Thread(starter); t.setDaemon(true); t.start(); } } boolean ramping = true; while (ramping) { boolean done = true; for (TestPlanStarter starter : testPlans) { done = done && starter.isDone(); } ramping = !done; if (ramping) { Thread.sleep(5000); } } // if we broke early, fix our countdown latch int numToCount = 0; for (TestPlanStarter starter : testPlans) { numToCount += starter.getThreadsStarted(); } while (numToCount < agentRunData.getNumUsers()) { doneSignal.countDown(); numToCount++; } // wait for them to finish LOG.info(LogUtil.getLogMessage("Ramp Complete...")); doneSignal.await(); } } catch (Throwable t) { LOG.error("error executing..." + t, t); } finally { LOG.info(LogUtil.getLogMessage("Test Complete...")); if (!isDebug() && NumberUtils.isDigits(agentRunData.getJobId())) { if (null != monitorThread) { APIMonitor.setJobStatus(JobStatus.Completed); APIMonitor.setDoMonitor(false); } sendBatchToDB(false); // sleep for 60 seconds to let wily agent clear any data try { Thread.sleep(60000); } catch (InterruptedException e) { // nothing to do } } } flowControllerTemplate.endTest(); // System.exit(0); }
From source file:org.sakaiproject.samigo.search.QuestionElasticSearchIndexBuilder.java
@Override protected void processContentQueue() { startTime = System.currentTimeMillis(); // If there are a lot of docs queued up this could take awhile we don't want // to eat up all the CPU cycles. Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1); if (getPendingDocuments() == 0) { getLog().trace("No pending docs for index builder [" + getName() + "]"); return;//w w w . j a v a2 s .c om } SearchResponse response = findContentQueue(); SearchHit[] hits = response.getHits().hits(); List<NoContentException> noContentExceptions = new ArrayList(); getLog().trace(getPendingDocuments() + " pending docs for index builder [" + getName() + "]"); BulkRequestBuilder bulkRequest = newContentQueueBulkUpdateRequestBuilder(); for (SearchHit hit : hits) { if (bulkRequest.numberOfActions() < bulkRequestSize) { try { processContentQueueEntry(hit, bulkRequest); } catch (NoContentException e) { noContentExceptions.add(e); } } else { executeBulkRequest(bulkRequest); bulkRequest = newContentQueueBulkUpdateRequestBuilder(); } } // execute any remaining bulks requests not executed yet if (bulkRequest.numberOfActions() > 0) { executeBulkRequest(bulkRequest); } // remove any docs without content, so we don't try to index them again if (!noContentExceptions.isEmpty()) { for (NoContentException noContentException : noContentExceptions) { deleteDocument(noContentException); } } lastLoad = System.currentTimeMillis(); if (hits.length > 0) { getLog().trace("Finished indexing " + hits.length + " docs in " + ((lastLoad - startTime)) + " ms for index builder " + getName()); } }
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 ww w. j a va 2 s. c o 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.sentaroh.android.TaskAutomation.TaskManager.java
static final private void startTaskOutsideThreadPool(final TaskManagerParms taskMgrParms, final EnvironmentParms envParms, final CommonUtilities util, final TaskExecutor tet) { if (envParms.statsUseOutsideThreadPoolCountTaskExec < Integer.MAX_VALUE) envParms.statsUseOutsideThreadPoolCountTaskExec++; else/* www . j a v a 2s .com*/ envParms.statsUseOutsideThreadPoolCountTaskExec = 1; util.addLogMsg("I", "Task was started by outside the thread pool. " + tet.toSting()); Thread th = new Thread() { @Override public void run() { tet.run(); } }; th.setPriority(Thread.NORM_PRIORITY - 3); th.start(); }
From source file:org.jdesktop.swingworker.AccumulativeRunnable.java
/** * returns workersExecutorService.// w ww. java2 s . c om * * 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; }