List of usage examples for java.lang Thread setPriority
public final void setPriority(int newPriority)
From source file:com.spoiledmilk.ibikecph.navigation.routing_engine.SMRoute.java
@Override public void onResponseReceived(int requestType, Object response) { switch (requestType) { case SMHttpRequest.REQUEST_GET_ROUTE: JsonNode jsonRoot = ((RouteInfo) response).jsonRoot; if (jsonRoot == null || jsonRoot.path("status").asInt(-1) != 0) { if (listener != null) listener.routeNotFound(); } else {//w w w. j a va 2 s . c o m setupRoute(jsonRoot); if (listener != null) listener.startRoute(); } break; case SMHttpRequest.REQUEST_GET_RECALCULATED_ROUTE: final JsonNode jRoot = ((RouteInfo) response).jsonRoot; if (jRoot == null || jRoot.path("status").asInt() != 0) { if (listener != null) { listener.serverError(); } recalculationInProgress = false; return; } final Handler h = new Handler(); Thread t = new Thread(new Runnable() { @Override public void run() { boolean ok = parseFromJson(jRoot, null, isRouteBroken); // logWaypoints(); if (ok) { approachingTurn = false; h.post(new Runnable() { @Override public void run() { if (lastLocation != null) { visitLocation(lastLocation); } if (visitedLocations != null && visitedLocations.size() > 0) { // visitLocation(visitedLocations.get(visitedLocations.size() - 1)); } if (SMLocationManager.getInstance().hasValidLocation()) { updateDistances(SMLocationManager.getInstance().getLastValidLocation()); } if (listener != null) { listener.routeRecalculationDone(); listener.updateRoute(); } recalculationInProgress = false; } }); } else { h.post(new Runnable() { @Override public void run() { if (listener != null) listener.serverError(); recalculationInProgress = false; } }); } } }); t.setPriority(Thread.MIN_PRIORITY); t.start(); } }
From source file:im.vector.util.VectorRoomMediasSender.java
/** * Offer to resize the image before sending it. * @param aThumbnailURL the thumbnail url * @param anImageUrl the image url./*from www. java 2s . com*/ * @param anImageFilename the image filename * @param anImageMimeType the image mimetype * @param aListener the listener */ private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename, final String anImageMimeType, final OnImageUploadListener aListener) { // sanity check if ((null == anImageUrl) || (null == aListener)) { return; } boolean isManaged = false; // check if the media could be resized if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType) || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType) || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) { System.gc(); FileInputStream imageStream; try { Uri uri = Uri.parse(anImageUrl); final String filename = uri.getPath(); final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, uri); imageStream = new FileInputStream(new File(filename)); int fileSize = imageStream.available(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.outWidth = -1; options.outHeight = -1; // retrieve the image size try { BitmapFactory.decodeStream(imageStream, null, options); } catch (OutOfMemoryError e) { Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage()); } final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight); imageStream.close(); // the user already selects a compression if (null != mImageCompressionDescription) { isManaged = true; final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity, mImageCompressionDescription); final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize, expectedSize, rotationAngle); mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorMessageListFragment.uploadImageContent(aThumbnailURL, fImageUrl, anImageFilename, anImageMimeType); aListener.onDone(); } }); } // can be rescaled ? else if (null != imageSizes.mSmallImageSize) { isManaged = true; FragmentManager fm = mVectorRoomActivity.getSupportFragmentManager(); ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes, fileSize); final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity); alert.setTitle(mVectorRoomActivity.getString(im.vector.R.string.compression_options)); alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final int fPos = which; mImageSizesListDialog.dismiss(); mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorRoomActivity.setProgressVisibility(View.VISIBLE); Thread thread = new Thread(new Runnable() { @Override public void run() { ImageSize expectedSize = null; // full size if (0 != fPos) { expectedSize = imageSizes.getImageSizesList().get(fPos); } // stored the compression selected by the user mImageCompressionDescription = imageSizes .getImageSizesDescription(mVectorRoomActivity).get(fPos); final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize, expectedSize, rotationAngle); mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorMessageListFragment.uploadImageContent(aThumbnailURL, fImageUrl, anImageFilename, anImageMimeType); aListener.onDone(); } }); } }); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } }); } }); mImageSizesListDialog = alert.show(); mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mImageSizesListDialog = null; if (null != aListener) { aListener.onCancel(); } } }); } } catch (Exception e) { Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage()); } } // cannot resize, let assumes that it has been done if (!isManaged) { mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorMessageListFragment.uploadImageContent(aThumbnailURL, anImageUrl, anImageFilename, anImageMimeType); if (null != aListener) { aListener.onDone(); } } }); } }
From source file:JNLPAppletLauncher.java
public void start() { if (DEBUG) {//from w w w. j a v a 2s. c o m System.err.println("Applet.start"); } if (isInitOk) { if (firstStart) { // first time firstStart = false; Thread startupThread = new Thread() { public void run() { initAndStartApplet(); } }; startupThread.setName("AppletLauncher-Startup"); startupThread.setPriority(Thread.NORM_PRIORITY - 1); startupThread.start(); } else if (appletStarted) { checkNoDDrawAndUpdateDeploymentProperties(); // We have to start again the applet (start can be called multiple times, // e.g once per tabbed browsing subApplet.start(); } } }
From source file:im.neon.util.VectorRoomMediasSender.java
/** * Offer to resize the image before sending it. * @param aThumbnailURL the thumbnail url * @param anImageUrl the image url./*w w w . j a va 2 s . co m*/ * @param anImageFilename the image filename * @param anImageMimeType the image mimetype * @param aListener the listener */ private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename, final String anImageMimeType, final OnImageUploadListener aListener) { // sanity check if ((null == anImageUrl) || (null == aListener)) { return; } boolean isManaged = false; // check if the media could be resized if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType) || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType) || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) { System.gc(); FileInputStream imageStream; try { Uri uri = Uri.parse(anImageUrl); final String filename = uri.getPath(); final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, uri); imageStream = new FileInputStream(new File(filename)); int fileSize = imageStream.available(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.outWidth = -1; options.outHeight = -1; // retrieve the image size try { BitmapFactory.decodeStream(imageStream, null, options); } catch (OutOfMemoryError e) { Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage()); } final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight); imageStream.close(); // the user already selects a compression if (null != mImageCompressionDescription) { isManaged = true; final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity, mImageCompressionDescription); final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize, expectedSize, rotationAngle); mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, fImageUrl, anImageFilename, anImageMimeType); aListener.onDone(); } }); } // can be rescaled ? else if (null != imageSizes.mSmallImageSize) { isManaged = true; FragmentManager fm = mVectorRoomActivity.getSupportFragmentManager(); ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes, fileSize); final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity); alert.setTitle(mVectorRoomActivity.getString(im.neon.R.string.compression_options)); alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final int fPos = which; mImageSizesListDialog.dismiss(); mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorRoomActivity.setProgressVisibility(View.VISIBLE); Thread thread = new Thread(new Runnable() { @Override public void run() { ImageSize expectedSize = null; // full size if (0 != fPos) { expectedSize = imageSizes.getImageSizesList().get(fPos); } // stored the compression selected by the user mImageCompressionDescription = imageSizes .getImageSizesDescription(mVectorRoomActivity).get(fPos); final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize, expectedSize, rotationAngle); mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, fImageUrl, anImageFilename, anImageMimeType); aListener.onDone(); } }); } }); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } }); } }); mImageSizesListDialog = alert.show(); mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mImageSizesListDialog = null; if (null != aListener) { aListener.onCancel(); } } }); } } catch (Exception e) { Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage()); } } // cannot resize, let assumes that it has been done if (!isManaged) { mVectorRoomActivity.runOnUiThread(new Runnable() { @Override public void run() { mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, anImageUrl, anImageFilename, anImageMimeType); if (null != aListener) { aListener.onDone(); } } }); } }
From source file:org.apache.hadoop.hbase.client.TestAdmin.java
void splitTest(byte[] splitPoint, byte[][] familyNames, int[] rowCounts, int numVersions, int blockSize) throws Exception { TableName tableName = TableName.valueOf("testForceSplit"); StringBuilder sb = new StringBuilder(); // Add tail to String so can see better in logs where a test is running. for (int i = 0; i < rowCounts.length; i++) { sb.append("_").append(Integer.toString(rowCounts[i])); }/* w ww . j av a 2s . c o m*/ assertFalse(admin.tableExists(tableName)); final HTable table = TEST_UTIL.createTable(tableName, familyNames, numVersions, blockSize); int rowCount = 0; byte[] q = new byte[0]; // insert rows into column families. The number of rows that have values // in a specific column family is decided by rowCounts[familyIndex] for (int index = 0; index < familyNames.length; index++) { ArrayList<Put> puts = new ArrayList<Put>(rowCounts[index]); for (int i = 0; i < rowCounts[index]; i++) { byte[] k = Bytes.toBytes(i); Put put = new Put(k); put.add(familyNames[index], q, k); puts.add(put); } table.put(puts); if (rowCount < rowCounts[index]) { rowCount = rowCounts[index]; } } // get the initial layout (should just be one region) Map<HRegionInfo, ServerName> m = table.getRegionLocations(); LOG.info("Initial regions (" + m.size() + "): " + m); assertTrue(m.size() == 1); // Verify row count Scan scan = new Scan(); ResultScanner scanner = table.getScanner(scan); int rows = 0; for (@SuppressWarnings("unused") Result result : scanner) { rows++; } scanner.close(); assertEquals(rowCount, rows); // Have an outstanding scan going on to make sure we can scan over splits. scan = new Scan(); scanner = table.getScanner(scan); // Scan first row so we are into first region before split happens. scanner.next(); // Split the table this.admin.split(tableName.getName(), splitPoint); final AtomicInteger count = new AtomicInteger(0); Thread t = new Thread("CheckForSplit") { public void run() { for (int i = 0; i < 45; i++) { try { sleep(1000); } catch (InterruptedException e) { continue; } // check again table = new HTable(conf, tableName); Map<HRegionInfo, ServerName> regions = null; try { regions = table.getRegionLocations(); } catch (IOException e) { e.printStackTrace(); } if (regions == null) continue; count.set(regions.size()); if (count.get() >= 2) { LOG.info("Found: " + regions); break; } LOG.debug("Cycle waiting on split"); } LOG.debug("CheckForSplit thread exited, current region count: " + count.get()); } }; t.setPriority(Thread.NORM_PRIORITY - 2); t.start(); t.join(); // Verify row count rows = 1; // We counted one row above. for (@SuppressWarnings("unused") Result result : scanner) { rows++; if (rows > rowCount) { scanner.close(); assertTrue("Scanned more than expected (" + rowCount + ")", false); } } scanner.close(); assertEquals(rowCount, rows); Map<HRegionInfo, ServerName> regions = null; try { regions = table.getRegionLocations(); } catch (IOException e) { e.printStackTrace(); } assertEquals(2, regions.size()); Set<HRegionInfo> hRegionInfos = regions.keySet(); HRegionInfo[] r = hRegionInfos.toArray(new HRegionInfo[hRegionInfos.size()]); if (splitPoint != null) { // make sure the split point matches our explicit configuration assertEquals(Bytes.toString(splitPoint), Bytes.toString(r[0].getEndKey())); assertEquals(Bytes.toString(splitPoint), Bytes.toString(r[1].getStartKey())); LOG.debug("Properly split on " + Bytes.toString(splitPoint)); } else { if (familyNames.length > 1) { int splitKey = Bytes.toInt(r[0].getEndKey()); // check if splitKey is based on the largest column family // in terms of it store size int deltaForLargestFamily = Math.abs(rowCount / 2 - splitKey); LOG.debug( "SplitKey=" + splitKey + "&deltaForLargestFamily=" + deltaForLargestFamily + ", r=" + r[0]); for (int index = 0; index < familyNames.length; index++) { int delta = Math.abs(rowCounts[index] / 2 - splitKey); if (delta < deltaForLargestFamily) { assertTrue( "Delta " + delta + " for family " + index + " should be at least deltaForLargestFamily " + deltaForLargestFamily, false); } } } } TEST_UTIL.deleteTable(tableName); table.close(); }
From source file:fs.MainWindow.java
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed jProgressBarSE.setValue(0);/* w w w . j av a2 s. c om*/ double alpha = (Double) jS_AlphaSE.getValue(); double q_entropy = (Double) jS_QEntropySE.getValue(); if (q_entropy < 0 || alpha < 0) { //entrada de dados invalida. JOptionPane.showMessageDialog(null, "Error on parameter value:" + " The values of q-entropy and Alpha must be positives.", "Application Error", JOptionPane.ERROR_MESSAGE); return; } class Thread1 extends Thread { @Override public void run() { try { if (jRB_SFSSE.isSelected()) { ExecuteFeatureSelection(1);// SFS } else if (jRB_ESSE.isSelected()) { ExecuteFeatureSelection(2);// ExhaustiveSearch } else if (jRB_SFFSSE.isSelected()) { ExecuteFeatureSelection(3);// SFFS } else { JOptionPane.showMessageDialog(null, "Select Feature " + "Selector must be marked.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (IOException error) { throw new FSException("Error on Execution of the Search" + " Method." + error, false); } } } Thread thread = new Thread1(); thread.setPriority(Thread.NORM_PRIORITY); thread.setName("SE"); thread.start(); }
From source file:fs.MainWindow.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed double alpha = (Double) jS_AlphaCV.getValue(); double q_entropy = (Double) jS_QEntropyCV.getValue(); if (q_entropy < 0 || alpha < 0) { //entrada de dados invalida. JOptionPane.showMessageDialog(null, "Error on parameter value:" + " The values of q-entropy and Alpha must be positives.", "Application Error", JOptionPane.ERROR_MESSAGE); return;//w w w . j av a 2 s . co m } class ThreadCV extends Thread { @Override public void run() { try { if (jRB_SFSCV.isSelected()) { CrossValidation((Integer) jS_NrExecutionsCV.getValue(), ((float) jSliderCV.getValue()) / 100, 1);// SFS } else if (jRB_ESCV.isSelected()) { CrossValidation((Integer) jS_NrExecutionsCV.getValue(), ((float) jSliderCV.getValue()) / 100, 2);//ExhaustiveSearch } else if (jRB_SFFSCV.isSelected()) { CrossValidation((Integer) jS_NrExecutionsCV.getValue(), ((float) jSliderCV.getValue()) / 100, 3);// SFFS } else { JOptionPane.showMessageDialog(null, "Select Feature " + "Selector must be marked.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (IOException error) { throw new FSException("Error on Cross-validation." + error, false); } } } Thread thread = new ThreadCV(); thread.setPriority(Thread.NORM_PRIORITY); thread.setName("CV"); thread.start(); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java
protected void generateThumbnailsInBackground(final List<WorkbenchRowImage> rowImages) { Collections.sort(rowImages);//from ww w. j av a 2 s . c om Thread thumbGenTask = new Thread() { @Override @SuppressWarnings("synthetic-access") public void run() { // This is just a weird workaround. // For some reason, using the List directly resulted in a ConcurrentModificationException everytime // this method was called from addImages(). // It doesn't look like it should throw an exception at all. WorkbenchRowImage[] imgs = new WorkbenchRowImage[rowImages.size()]; rowImages.toArray(imgs); for (WorkbenchRowImage rowImage : imgs) { final WorkbenchRowImage ri = rowImage; try { final ImageIcon thumb = generateThumbnail(rowImage); // cache it so we don't have to do this again and again rowImage.setThumbnail(thumb); // update the UI Runnable updateTrayUI = new Runnable() { public void run() { log.info("Thumbnail generation complete. Updating the UI. " + ri); if (row == ri.getWorkbenchRow()) { tray.getModel().set(ri.getImageOrder(), thumb); tray.repaint(); } } }; SwingUtilities.invokeLater(updateTrayUI); } catch (IOException e) { UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImageFrame.class, e); log.warn("Failed to generate a thumbnail for " + rowImage.getCardImageFullPath(), e); } } } }; thumbGenTask.setName("GenThumbs"); thumbGenTask.setDaemon(true); thumbGenTask.setPriority(Thread.MIN_PRIORITY); thumbGenTask.start(); }
From source file:org.apache.log4j.chainsaw.LogUI.java
/** * Initialises the menu's and toolbars, but does not actually create any of * the main panel components./*from w w w .j av a2 s . c om*/ * */ private void initGUI() { setupHelpSystem(); statusBar = new ChainsawStatusBar(this); setupReceiverPanel(); setToolBarAndMenus(new ChainsawToolBarAndMenus(this)); toolbar = getToolBarAndMenus().getToolbar(); setJMenuBar(getToolBarAndMenus().getMenubar()); setTabbedPane(new ChainsawTabbedPane()); getSettingsManager().addSettingsListener(getTabbedPane()); getSettingsManager().configure(getTabbedPane()); /** * This adds Drag & Drop capability to Chainsaw */ FileDnDTarget dnDTarget = new FileDnDTarget(tabbedPane); dnDTarget.addPropertyChangeListener("fileList", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { final List fileList = (List) evt.getNewValue(); Thread thread = new Thread(new Runnable() { public void run() { logger.debug("Loading files: " + fileList); for (Iterator iter = fileList.iterator(); iter.hasNext();) { File file = (File) iter.next(); final Decoder decoder = new XMLDecoder(); try { getStatusBar().setMessage("Loading " + file.getAbsolutePath() + "..."); FileLoadAction.importURL(handler, decoder, file.getName(), file.toURI().toURL()); } catch (Exception e) { String errorMsg = "Failed to import a file"; logger.error(errorMsg, e); getStatusBar().setMessage(errorMsg); } } } }); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } }); applicationPreferenceModelPanel = new ApplicationPreferenceModelPanel(applicationPreferenceModel); applicationPreferenceModelPanel.setOkCancelActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { preferencesFrame.setVisible(false); } }); KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { preferencesFrame.setVisible(false); } }; preferencesFrame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE"); preferencesFrame.getRootPane().getActionMap().put("ESCAPE", closeAction); OSXIntegration.init(this); }
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//w w w. ja v a 2 s . co 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(); } } }); }