List of usage examples for java.lang Thread setPriority
public final void setPriority(int newPriority)
From source file:com.amazonservices.mws.client.MwsConnection.java
/** * Get the shared executor service that is used by async calls if no * executor is supplied./* www .ja v a 2 s . com*/ * * @return The shared executor service. */ private ExecutorService getSharedES() { synchronized (this.getClass()) { if (sharedES != null) { return sharedES; } sharedES = new ThreadPoolExecutor(maxAsyncThreads / 10, maxAsyncThreads, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maxAsyncQueueSize), new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); //@Override public Thread newThread(Runnable task) { Thread thread = new Thread(task, "MWSClient-" + threadNumber.getAndIncrement()); thread.setDaemon(true); thread.setPriority(Thread.NORM_PRIORITY); return thread; } }, new RejectedExecutionHandler() { //@Override public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) { if (!executor.isShutdown()) { log.warn("MWSClient async queue full, running on calling thread."); task.run(); } else { throw new RejectedExecutionException(); } } }); return sharedES; } }
From source file:org.dawnsci.commandserver.ui.view.ConsumerView.java
@Override public void createPartControl(Composite content) { content.setLayout(new GridLayout(1, false)); GridUtils.removeMargins(content);/* w ww . j a va 2 s . c o m*/ this.viewer = new TableViewer(content, SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); viewer.setUseHashlookup(true); viewer.getTable().setHeaderVisible(true); viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createColumns(); viewer.setContentProvider(createContentProvider()); consumers = new TreeMap<String, ConsumerBean>(Collections.reverseOrder()); viewer.setInput(consumers); createActions(); try { createTopicListener(getUri()); } catch (Exception e) { logger.error("Cannot listen to topic of command server!", e); } final Thread job = new Thread(new Runnable() { @Override public void run() { while (!viewer.getTable().isDisposed()) { try { Thread.sleep(Constants.NOTIFICATION_FREQUENCY); if (viewer.getControl().isDisposed()) return; viewer.getControl().getDisplay().syncExec(new Runnable() { public void run() { viewer.refresh(); } }); } catch (InterruptedException e) { return; } } } }); job.setPriority(Thread.MIN_PRIORITY); job.setDaemon(true); job.setName("Refresh consumer table"); job.start(); }
From source file:free.chessclub.bot.Bot.java
public void positionChanged(PositionChangedEvent evt) { int lastScore; System.err.println("position changed"); Integer gameNumber = findMyGame(); JinFreechessConnection.InternalGameData gameData = (JinFreechessConnection.InternalGameData) ongoingGamesData .get(gameNumber);// w w w.j a v a 2s . c o m Move move = makeGameMovesOnBoard(gameData, gameBoard); if (gameBoard.isDraw()) { if (tellOwner) sendCommand("tell " + owner + " Claiming draw"); evt.getConnection().sendCommand("draw"); } // if(move != null) evt.getConnection().sendCommand("tell " + owner + " board move: " + move.toString()); if (evt.getGame().isUserAllowedToMovePieces(evt.getPosition().getCurrentPlayer()) && (!currentSearchEPD.equals(evt.getGame().getInitialPosition().getFEN()) || evt.getGame().getPliesSinceStart() == 0)) { if (!iterativeSearch.isDone()) { System.err.println("Waiting for search..."); try { searchThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println("Search complete."); } Board searchBoard = new Board(); // searchBoard.setEPDPosition(gameData.boardData.getBoardFEN()); currentSearchEPD = evt.getGame().getInitialPosition().getFEN(); searchBoard.setEPDPosition(evt.getGame().getInitialPosition().getFEN()); searchBoard.turn = evt.getGame().getUserPlayer().isWhite() ? 1 : 0; searchBoard.stats = gameBoard.stats; searchBoard.stats.whiteKingsideRookMoves = gameData.boardData.canWhiteCastleKingside() ? 0 : 1; searchBoard.stats.whiteQueensideRookMoves = gameData.boardData.canWhiteCastleQueenside() ? 0 : 1; searchBoard.stats.blackKingsideRookMoves = gameData.boardData.canBlackCastleKingside() ? 0 : 1; searchBoard.stats.blackQueensideRookMoves = gameData.boardData.canBlackCastleQueenside() ? 0 : 1; searchBoard.repetitionTable = gameBoard.repetitionTable; searchBoard.fiftyMoveTable = gameBoard.fiftyMoveTable; searchBoard.moveIndex = gameBoard.moveIndex; for (int t = 0; t < 128; t++) { if (gameBoard.boardSquares[t] == null) { continue; } System.arraycopy(gameBoard.boardSquares[t].enPassentInfo, 0, searchBoard.boardSquares[t].enPassentInfo, 0, searchBoard.boardSquares[t].enPassentInfo.length); } // searchBoard.moveHistory = gameBoard.moveHistory; /* searchBoard.hash1 = gameBoard.hash1; searchBoard.pawnHash = gameBoard.pawnHash; */ iterativeSearch.reset(); searchThread = new Thread(new SearchThread(evt.getConnection(), iterativeSearch, searchBoard)); searchThread.setPriority(6); searchThread.start(); String fen = gameData.boardData.getBoardFEN(); System.err.println("MoveIndex: " + searchBoard.moveIndex); System.err.println("GB Approaching Draw: " + gameBoard.isApproachingDraw()); System.err.println("SB Approaching Draw: " + searchBoard.isApproachingDraw()); System.err.println("Board: " + fen); System.err.println("Stats: " + searchBoard.stats); int score = eval.scorePosition(searchBoard, -Searcher.INFINITY, Searcher.INFINITY); System.err.println("Searching (" + formatScore(score) + ") ..."); System.err.println(searchBoard.toString()); long maxTime = getTimeForMove(evt, gameData); Thread searchTimerThread = new Thread( new SearchTimerThread(evt.getConnection(), iterativeSearch, maxTime, fen)); searchTimerThread.setPriority(7); searchTimerThread.start(); } else { System.err.println("Waiting for opponent..."); // System.gc(); } }
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();//w w w. j a va2s .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:net.yacy.http.ProxyHandler.java
private void storeToCache(final Response yacyResponse, final byte[] cacheArray) { final Thread t = new Thread() { @Override//www . j a v a2s . com public void run() { if (yacyResponse == null) return; this.setName("ProxyHandler.storeToCache(" + yacyResponse.url().toNormalform(true) + ")"); // the cache does either not exist or is (supposed to be) stale deleteFromCache(yacyResponse.url().hash()); if (cacheArray == null || cacheArray.length <= 0) return; yacyResponse.setContent(cacheArray); try { Cache.store(yacyResponse.url(), yacyResponse.getResponseHeader(), cacheArray); sb.toIndexer(yacyResponse); } catch (IOException e) { //log.logWarning("cannot write " + response.url() + " to Cache (1): " + e.getMessage(), e); } } }; t.setPriority(Thread.MIN_PRIORITY); t.start(); }
From source file:org.madsonic.service.MediaScannerService.java
/** * Scans the media library./*ww w . j av a2 s. com*/ * The scanning is done asynchronously, i.e., this method returns immediately. */ public synchronized void scanLibrary() { if (isScanning()) { return; } scanning = true; Thread thread = new Thread("MediaLibraryScanner") { @Override public void run() { doScanLibrary(); // //TODO: rework // List<Artist> allArtists = artistDao.getAllArtists(); // LOG.info("## ArtistCount: " + allArtists.size()); // // lastFMService.test(allArtists); playlistService.importPlaylists(); playlistService.updatePlaylistStatistics(); } }; thread.setPriority(Thread.MIN_PRIORITY); thread.start(); }
From source file:org.scale7.cassandra.pelops.pool.CommonsBackedPool.java
private void configureScheduledTasks() { if (policy.getTimeBetweenScheduledMaintenanceTaskRunsMillis() > 0) { if (policy.isRunMaintenanceTaskDuringInit()) { logger.info("Running maintenance tasks during initialization..."); runMaintenanceTasks();/*from w w w .j av a 2 s.co m*/ } if (Policy.MIN_TIME_BETWEEN_SCHEDULED_TASKS >= policy .getTimeBetweenScheduledMaintenanceTaskRunsMillis()) { logger.warn( "Setting the scheduled tasks to run less than every {} milliseconds is not a good idea...", Policy.MIN_TIME_BETWEEN_SCHEDULED_TASKS); } logger.info("Configuring scheduled tasks to run every {} milliseconds", policy.getTimeBetweenScheduledMaintenanceTaskRunsMillis()); executorService = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "pelops-pool-worker-" + getKeyspace()); thread.setDaemon(true); // don't make the JVM wait for this thread to exit thread.setPriority(Thread.MIN_PRIORITY + 1); // try not to disrupt other threads return thread; } }); executorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { logger.debug("Background thread running maintenance tasks"); try { runMaintenanceTasks(); } catch (Exception e) { logger.warn("An exception was thrown while running the maintenance tasks", e); } } }, policy.getTimeBetweenScheduledMaintenanceTaskRunsMillis(), policy.getTimeBetweenScheduledMaintenanceTaskRunsMillis(), TimeUnit.MILLISECONDS); } else { logger.warn("Disabling maintenance tasks; dynamic node discovery, node suspension, idle connection " + "termination and some running statistics will not be available to this pool."); } }
From source file:com.liferay.portal.plugin.PluginPackageUtil.java
private boolean _isUpdateAvailable() throws SystemException { if (!PrefsPropsUtil.getBoolean(PropsKeys.PLUGIN_NOTIFICATIONS_ENABLED, PropsValues.PLUGIN_NOTIFICATIONS_ENABLED)) { return false; }//from w ww. j a va 2s .co m if (_updateAvailable != null) { return _updateAvailable.booleanValue(); } else if (!_settingUpdateAvailable) { _settingUpdateAvailable = true; Thread indexerThread = new Thread(new UpdateAvailableRunner(), PluginPackageUtil.class.getName()); indexerThread.setPriority(Thread.MIN_PRIORITY); indexerThread.start(); } return false; }
From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java
/** * Callback for the preview renderer to indicate a finished rendering * operation./*w ww . j a v a2 s.co m*/ * * @param resource * the resource */ void previewCreated(Resource<?> resource) { synchronized (currentPreviewOperations) { // Do the cleanup for (Iterator<PreviewOperation> i = currentPreviewOperations.iterator(); i.hasNext();) { PreviewOperation op = i.next(); Resource<?> r = op.getResource(); if (r.equals(resource)) { logger.debug("Preview creation of {} finished", r.getURI()); i.remove(); PreviewOperation o = previews.get(r.getURI()); // In the meantime, someone may have canceled this operation and // created a new one if (op == o) previews.remove(r.getURI()); break; } } // Is there more work to do? if (!previewOperations.isEmpty() && currentPreviewOperations.size() < maxPreviewOperations) { // Get the next operation and do the bookkeeping PreviewOperation op = previewOperations.remove(); Resource<?> r = op.getResource(); currentPreviewOperations.add(op); // Finally start the generation PreviewGeneratorWorker previewWorker = new PreviewGeneratorWorker(this, r, environment, op.getLanguages(), op.getStyles(), op.getFormat()); op.setWorker(previewWorker); Thread t = new Thread(previewWorker); t.setPriority(Thread.MIN_PRIORITY); t.setDaemon(true); logger.debug("Starting creation of preview of {}", r.getURI()); logger.trace("There are {} more preview operations waiting", previewOperations.size()); logger.trace("Currently using {} out of {} preview creation slots", currentPreviewOperations.size(), maxPreviewOperations); t.start(); } else { logger.debug("No more resources queued for preview creation"); } } }
From source file:org.jumpmind.symmetric.service.impl.DataLoaderService.java
public void start() { dataLoadWorkers = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() { final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix = parameterService.getEngineName().toLowerCase() + "-data-load-worker-"; public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName(namePrefix + threadNumber.getAndIncrement()); t.setDaemon(false);/* www . j a va2s . c o m*/ if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }); }