List of usage examples for java.lang Thread MIN_PRIORITY
int MIN_PRIORITY
To view the source code for java.lang Thread MIN_PRIORITY.
Click Source Link
From source file:net.sf.profiler4j.console.util.task.LongTaskExecutorDialog.java
public void runTask(final LongTask task) { label.setText("Executing long-running task..."); task.setDialog(this); Thread t = new Thread("PROFILER4J_TASK") { public void run() { log.debug("TASK STARTED"); try { task.executeInBackground(); } catch (final Exception e) { SwingUtilities.invokeLater(new Runnable() { public void run() { log.error("Caught task error", e); error = e;//from w w w . j av a 2 s . c om }; }); } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { log.debug("TASK COMPLETED"); if (error != null) { setDefaultCloseOperation(DISPOSE_ON_CLOSE); progressBar.setIndeterminate(false); setSize(486, 379); setVisible(true); toFront(); ((JComponent) statusTextArea.getParent()).revalidate(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); error.printStackTrace(pw); statusTextArea.setText(sw.toString()); statusTextArea.setCaretPosition(0); task.setError(error); } else { setVisible(false); dispose(); } } }); } }; }; t.setName("LongTaskRunner"); t.setPriority(Thread.MIN_PRIORITY); t.setDaemon(false); t.start(); setLocation(getLocation().x, getLocation().y - 120); setVisible(true); }
From source file:com.ubuntuone.android.files.service.MetaService.java
@Override protected void onHandleIntent(Intent intent) { sSyncRunning = true;// ww w.ja v a 2s .com Thread.currentThread().setPriority(Thread.MIN_PRIORITY); final String action = intent.getAction(); final String resourcePath = intent.getStringExtra(EXTRA_RESOURCE_PATH); final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_CALLBACK); if (ACTION_GET_USER.equals(action)) { getUser(receiver); getVolumes(receiver); } else if (ACTION_GET_VOLUME.equals(action)) { getVolume(resourcePath, receiver); } else if (ACTION_CREATE_VOLUME.equals(action)) { createVolume(resourcePath, receiver); } else if (ACTION_MAKE_DIRECTORY.equals(action)) { makeDirectory(resourcePath, receiver); } else if (ACTION_GET_NODE.equals(action)) { getNode(resourcePath, receiver, true); } else if (ACTION_UPDATE_NODE.equals(action)) { if (intent.hasExtra(Nodes.NODE_NAME)) { String newPath = intent.getStringExtra(EXTRA_PATH); updateNode(resourcePath, newPath, receiver); } if (intent.hasExtra(Nodes.NODE_IS_PUBLIC)) { Boolean isPublic = intent.getBooleanExtra(Nodes.NODE_IS_PUBLIC, false); updateNode(resourcePath, isPublic, receiver); } } else if (ACTION_DELETE_NODE.equals(action)) { deleteNode(resourcePath, receiver); } sSyncRunning = false; }
From source file:org.apache.blur.store.blockcache_v2.BaseCache.java
public BaseCache(long totalNumberOfBytes, Size fileBufferSize, Size cacheBlockSize, Size directLocalCacheRefLimit, FileNameFilter readFilter, FileNameFilter writeFilter, Quiet quiet, BaseCacheValueBufferPool cacheValueBufferPool) { _cacheMap = new ConcurrentLinkedHashMap.Builder<CacheKey, CacheValue>().weigher(new BaseCacheWeigher()) .maximumWeightedCapacity(totalNumberOfBytes).listener(new BaseCacheEvictionListener()).build(); _fileBufferSize = fileBufferSize;/* w w w . j a v a 2s .c om*/ _readFilter = readFilter; _writeFilter = writeFilter; _cacheBlockSize = cacheBlockSize; _directLocalCacheRefLimit = directLocalCacheRefLimit; _quiet = quiet; _hits = MeterWrapper .wrap(Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, CACHE, HIT), HIT, TimeUnit.SECONDS)); _misses = MeterWrapper .wrap(Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, CACHE, MISS), MISS, TimeUnit.SECONDS)); _evictions = MeterWrapper.wrap( Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, CACHE, EVICTION), EVICTION, TimeUnit.SECONDS)); _removals = MeterWrapper .wrap(Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, CACHE, REMOVAL), REMOVAL, TimeUnit.SECONDS)); _cacheValueBufferPool = cacheValueBufferPool; Metrics.newGauge(new MetricName(ORG_APACHE_BLUR, CACHE, ENTRIES), new Gauge<Long>() { @Override public Long value() { return (long) getEntryCount(); } }); Metrics.newGauge(new MetricName(ORG_APACHE_BLUR, CACHE, SIZE), new Gauge<Long>() { @Override public Long value() { return getWeightedSize(); } }); _oldFileDaemonThread = new Thread(new Runnable() { @Override public void run() { while (_running.get()) { cleanupOldFiles(); try { Thread.sleep(_1_MINUTE); } catch (InterruptedException e) { return; } } } }); _oldFileDaemonThread.setDaemon(true); _oldFileDaemonThread.setName("BaseCacheOldFileCleanup"); _oldFileDaemonThread.setPriority(Thread.MIN_PRIORITY); _oldFileDaemonThread.start(); }
From source file:org.xwiki.job.internal.DefaultJobStatusStore.java
@Override public void initialize() throws InitializationException { try {// w w w. j a v a2 s . c om this.serializer = new JobStatusSerializer(); repair(); } catch (Exception e) { this.logger.error("Failed to load jobs", e); } BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Job status serializer") .daemon(true).priority(Thread.MIN_PRIORITY).build(); this.executorService = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); this.cache = Collections.synchronizedMap(new Cache(this.configuration.getJobStatusCacheSize())); }
From source file:tvbrowser.TVBrowser.java
/** * Entry point of the application//w w w . j a v a 2 s. c om * @param args The arguments given in the command line. */ public static void main(String[] args) { // Read the command line parameters parseCommandline(args); try { Toolkit.getDefaultToolkit().setDynamicLayout( (Boolean) Toolkit.getDefaultToolkit().getDesktopProperty("awt.dynamicLayoutSupported")); } catch (Exception e) { e.printStackTrace(); } mLocalizer = util.ui.Localizer.getLocalizerFor(TVBrowser.class); // Check whether the TV-Browser was started in the right directory if (!new File("imgs").exists()) { String msg = "Please start TV-Browser in the TV-Browser directory!"; if (mLocalizer != null) { msg = mLocalizer.msg("error.2", "Please start TV-Browser in the TV-Browser directory!"); } JOptionPane.showMessageDialog(null, msg); System.exit(1); } if (mIsTransportable) { System.getProperties().remove("propertiesfile"); } // setup logging // Get the default Logger Logger mainLogger = Logger.getLogger(""); // Use a even simpler Formatter for console logging mainLogger.getHandlers()[0].setFormatter(createFormatter()); if (mIsTransportable) { File settingsDir = new File("settings"); try { File test = File.createTempFile("write", "test", settingsDir); test.delete(); } catch (IOException e) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e1) { //ignore } JTextArea area = new JTextArea(mLocalizer.msg("error.noWriteRightsText", "You are using the transportable version of TV-Browser but you have no writing rights in the settings directory:\n\n{0}'\n\nTV-Browser will be closed.", settingsDir.getAbsolutePath())); area.setFont(new JLabel().getFont()); area.setFont(area.getFont().deriveFont((float) 14).deriveFont(Font.BOLD)); area.setLineWrap(true); area.setWrapStyleWord(true); area.setPreferredSize(new Dimension(500, 100)); area.setEditable(false); area.setBorder(null); area.setOpaque(false); JOptionPane.showMessageDialog(null, area, mLocalizer.msg("error.noWriteRightsTitle", "No write rights in settings directory"), JOptionPane.ERROR_MESSAGE); System.exit(1); } } // Load the settings Settings.loadSettings(); Locale.setDefault(new Locale(Settings.propLanguage.getString(), Settings.propCountry.getString())); if (Settings.propFirstStartDate.getDate() == null) { Settings.propFirstStartDate.setDate(Date.getCurrentDate()); } if (!createLockFile()) { updateLookAndFeel(); showTVBrowserIsAlreadyRunningMessageBox(); } String logDirectory = Settings.propLogdirectory.getString(); if (logDirectory != null) { try { File logDir = new File(logDirectory); logDir.mkdirs(); mainLogger.addHandler( new FileLoggingHandler(logDir.getAbsolutePath() + "/tvbrowser.log", createFormatter())); } catch (IOException exc) { String msg = mLocalizer.msg("error.4", "Can't create log file."); ErrorHandler.handle(msg, exc); } } else { // if no logging is configured, show WARNING or worse for normal usage, show everything for unstable versions if (TVBrowser.isStable()) { mainLogger.setLevel(Level.WARNING); } } // log warning for OpenJDK users if (!isJavaImplementationSupported()) { mainLogger.warning(SUN_JAVA_WARNING); } //Update plugin on version change if (Settings.propTVBrowserVersion.getVersion() != null && VERSION.compareTo(Settings.propTVBrowserVersion.getVersion()) > 0) { updateLookAndFeel(); updatePluginsOnVersionChange(); } // Capture unhandled exceptions //System.setErr(new PrintStream(new MonitoringErrorStream())); String timezone = Settings.propTimezone.getString(); if (timezone != null) { TimeZone.setDefault(TimeZone.getTimeZone(timezone)); } mLog.info("Using timezone " + TimeZone.getDefault().getDisplayName()); // refresh the localizers because we know the language now Localizer.emptyLocalizerCache(); mLocalizer = Localizer.getLocalizerFor(TVBrowser.class); ProgramInfo.resetLocalizer(); ReminderPlugin.resetLocalizer(); Date.resetLocalizer(); ProgramFieldType.resetLocalizer(); // Set the proxy settings updateProxySettings(); // Set the String to use for indicating the user agent in http requests System.setProperty("http.agent", MAINWINDOW_TITLE); Version tmpVer = Settings.propTVBrowserVersion.getVersion(); final Version currentVersion = tmpVer != null ? new Version(tmpVer.getMajor(), tmpVer.getMinor(), Settings.propTVBrowserVersionIsStable.getBoolean()) : tmpVer; /*TODO Create an update service for installed TV data services that doesn't * work with TV-Browser 3.0 and updates for them are known. */ if (!isTransportable() && Launch.isOsWindowsNtBranch() && currentVersion != null && currentVersion.compareTo(new Version(3, 0, true)) < 0) { String tvDataDir = Settings.propTVDataDirectory.getString().replace("/", File.separator); if (!tvDataDir.startsWith(System.getenv("appdata"))) { StringBuilder oldDefaultTvDataDir = new StringBuilder(System.getProperty("user.home")) .append(File.separator).append("TV-Browser").append(File.separator).append("tvdata"); if (oldDefaultTvDataDir.toString().equals(tvDataDir)) { Settings.propTVDataDirectory.setString(Settings.propTVDataDirectory.getDefault()); } } } Settings.propTVBrowserVersion.setVersion(VERSION); Settings.propTVBrowserVersionIsStable.setBoolean(VERSION.isStable()); final Splash splash; if (mShowSplashScreen && Settings.propSplashShow.getBoolean()) { splash = new SplashScreen(Settings.propSplashImage.getString(), Settings.propSplashTextPosX.getInt(), Settings.propSplashTextPosY.getInt(), Settings.propSplashForegroundColor.getColor()); } else { splash = new DummySplash(); } splash.showSplash(); /* Initialize the MarkedProgramsList */ MarkedProgramsList.getInstance(); /*Maybe there are tvdataservices to install (.jar.inst files)*/ PluginLoader.getInstance().installPendingPlugins(); PluginLoader.getInstance().loadAllPlugins(); mLog.info("Loading TV listings service..."); splash.setMessage(mLocalizer.msg("splash.dataService", "Loading TV listings service...")); TvDataServiceProxyManager.getInstance().init(); ChannelList.createForTvBrowserStart(); ChannelList.initSubscribedChannels(); if (!lookAndFeelInitialized) { mLog.info("Loading Look&Feel..."); splash.setMessage(mLocalizer.msg("splash.laf", "Loading look and feel...")); updateLookAndFeel(); } mLog.info("Loading plugins..."); splash.setMessage(mLocalizer.msg("splash.plugins", "Loading plugins...")); try { PluginProxyManager.getInstance().init(); } catch (TvBrowserException exc) { ErrorHandler.handle(exc); } splash.setMessage(mLocalizer.msg("splash.tvData", "Checking TV database...")); mLog.info("Checking TV listings inventory..."); TvDataBase.getInstance().checkTvDataInventory(); mLog.info("Starting up..."); splash.setMessage(mLocalizer.msg("splash.ui", "Starting up...")); Toolkit.getDefaultToolkit().getSystemEventQueue().push(new TextComponentPopupEventQueue()); // Init the UI final boolean fStartMinimized = Settings.propMinimizeAfterStartup.getBoolean() || mMinimized; SwingUtilities.invokeLater(new Runnable() { public void run() { initUi(splash, fStartMinimized); new Thread("Start finished callbacks") { public void run() { setPriority(Thread.MIN_PRIORITY); mLog.info("Deleting expired TV listings..."); TvDataBase.getInstance().deleteExpiredFiles(1, false); // first reset "starting" flag of mainframe mainFrame.handleTvBrowserStartFinished(); // initialize program info for fast reaction to program table click ProgramInfo.getInstance().handleTvBrowserStartFinished(); // load reminders and favorites ReminderPlugin.getInstance().handleTvBrowserStartFinished(); FavoritesPlugin.getInstance().handleTvBrowserStartFinished(); // now handle all plugins and services GlobalPluginProgramFormatingManager.getInstance(); PluginProxyManager.getInstance().fireTvBrowserStartFinished(); TvDataServiceProxyManager.getInstance().fireTvBrowserStartFinished(); // finally submit plugin caused updates to database TvDataBase.getInstance().handleTvBrowserStartFinished(); startPeriodicSaveSettings(); } }.start(); SwingUtilities.invokeLater(new Runnable() { public void run() { ChannelList.completeChannelLoading(); initializeAutomaticDownload(); if (Launch.isOsWindowsNtBranch()) { try { RegistryKey desktopSettings = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Control Panel\\Desktop"); RegistryValue autoEnd = desktopSettings.getValue("AutoEndTasks"); if (autoEnd.getData().equals("1")) { RegistryValue killWait = desktopSettings.getValue("WaitToKillAppTimeout"); int i = Integer.parseInt(killWait.getData().toString()); if (i < 5000) { JOptionPane pane = new JOptionPane(); String cancel = mLocalizer.msg("registryCancel", "Close TV-Browser"); String dontDoIt = mLocalizer.msg("registryJumpOver", "Not this time"); pane.setOptions(new String[] { Localizer.getLocalization(Localizer.I18N_OK), dontDoIt, cancel }); pane.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION); pane.setMessageType(JOptionPane.WARNING_MESSAGE); pane.setMessage(mLocalizer.msg("registryWarning", "The fast shutdown of Windows is activated.\nThe timeout to wait for before Windows is closing an application is too short,\nto give TV-Browser enough time to save all settings.\n\nThe setting hasn't the default value. It was changed by a tool or by you.\nTV-Browser will now try to change the timeout.\n\nIf you don't want to change this timeout select 'Not this time' or 'Close TV-Browser'.")); pane.setInitialValue(mLocalizer.msg("registryCancel", "Close TV-Browser")); JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(mainFrame), UIManager.getString("OptionPane.messageDialogTitle")); d.setModal(true); UiUtilities.centerAndShow(d); if (pane.getValue() == null || pane.getValue().equals(cancel)) { mainFrame.quit(); } else if (!pane.getValue().equals(dontDoIt)) { try { killWait.setData("5000"); desktopSettings.setValue(killWait); JOptionPane.showMessageDialog( UiUtilities.getLastModalChildOf(mainFrame), mLocalizer.msg("registryChanged", "The timeout was changed successfully.\nPlease reboot Windows!")); } catch (Exception registySetting) { JOptionPane.showMessageDialog( UiUtilities.getLastModalChildOf(mainFrame), mLocalizer.msg("registryNotChanged", "<html>The Registry value couldn't be changed. Maybe you haven't the right to do it.<br>If it is so contact you Administrator and let him do it for you.<br><br><b><Attention:/b> The following description is for experts. If you change or delete the wrong value in the Registry you could destroy your Windows installation.<br><br>To get no warning on TV-Browser start the Registry value <b>WaitToKillAppTimeout</b> in the Registry path<br><b>HKEY_CURRENT_USER\\Control Panel\\Desktop</b> have to be at least <b>5000</b> or the value for <b>AutoEndTasks</b> in the same path have to be <b>0</b>.</html>"), Localizer.getLocalization(Localizer.I18N_ERROR), JOptionPane.ERROR_MESSAGE); } } } } } catch (Throwable registry) { } } if (currentVersion != null && currentVersion.compareTo(new Version(2, 71, false)) < 0) { if (Settings.propProgramPanelMarkedMinPriorityColor.getColor() .equals(Settings.propProgramPanelMarkedMinPriorityColor.getDefaultColor())) { Settings.propProgramPanelMarkedMinPriorityColor.setColor(new Color(255, 0, 0, 30)); } if (Settings.propProgramPanelMarkedMediumPriorityColor.getColor() .equals(Settings.propProgramPanelMarkedMediumPriorityColor.getDefaultColor())) { Settings.propProgramPanelMarkedMediumPriorityColor .setColor(new Color(140, 255, 0, 60)); } if (Settings.propProgramPanelMarkedHigherMediumPriorityColor.getColor().equals( Settings.propProgramPanelMarkedHigherMediumPriorityColor.getDefaultColor())) { Settings.propProgramPanelMarkedHigherMediumPriorityColor .setColor(new Color(255, 255, 0, 60)); } if (Settings.propProgramPanelMarkedMaxPriorityColor.getColor() .equals(Settings.propProgramPanelMarkedMaxPriorityColor.getDefaultColor())) { Settings.propProgramPanelMarkedMaxPriorityColor .setColor(new Color(255, 180, 0, 110)); } } // check if user should select picture settings if (currentVersion != null && currentVersion.compareTo(new Version(2, 22)) < 0) { TvBrowserPictureSettingsUpdateDialog.createAndShow(mainFrame); } else if (currentVersion != null && currentVersion.compareTo(new Version(2, 51, true)) < 0) { Settings.propAcceptedLicenseArrForServiceIds.setStringArray(new String[0]); } if (currentVersion != null && currentVersion.compareTo(new Version(2, 60, true)) < 0) { int startOfDay = Settings.propProgramTableStartOfDay.getInt(); int endOfDay = Settings.propProgramTableEndOfDay.getInt(); if (endOfDay - startOfDay < -1) { Settings.propProgramTableEndOfDay.setInt(startOfDay); JOptionPane.showMessageDialog(UiUtilities.getLastModalChildOf(mainFrame), mLocalizer.msg("timeInfoText", "The time range of the program table was corrected because the defined day was shorter than 24 hours.\n\nIf the program table should show less than 24h use a time filter for that. That time filter can be selected\nto be the default filter by selecting it in the filter settings and pressing on the button 'Default'."), mLocalizer.msg("timeInfoTitle", "Times corrected"), JOptionPane.INFORMATION_MESSAGE); Settings.handleChangedSettings(); } } MainFrame.getInstance().getProgramTableScrollPane().requestFocusInWindow(); } }); } }); // register the shutdown hook Runtime.getRuntime().addShutdownHook(new Thread("Shutdown hook") { public void run() { deleteLockFile(); MainFrame.getInstance().quit(false); } }); }
From source file:TIG055st2014.mailmaster.Services.EmailNotificationService.java
@Override public void onCreate() { super.onCreate(); Toast.makeText(this, getApplicationContext().getResources().getString(R.string.toast_service_creat), Toast.LENGTH_LONG).show();//w w w . ja va 2 s .c o m thread = new Thread() { @Override public void run() { NotificationManager notifyManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); //Used for action that is triggered when notification is pressed/deleted. Intent emailIntent = new Intent(getApplicationContext(), EmailNotificationForwarder.class); accounts = getSharedPreferences("StoredAccounts", MODE_PRIVATE); pageNumbers = getSharedPreferences("pages", MODE_PRIVATE); activeAccs = new HashSet<String>(); activeAccs.addAll(accounts.getStringSet("default", new HashSet<String>())); /* * Contains the logic for autoupdating email list/notification */ while (running) { initVariables(); getLatest(); for (Message m : emails) { try { if (!m.getFlags().contains(Flag.SEEN)) { EmailNotificationVariables.nrUnreadEmail++; } } catch (Exception e) { e.printStackTrace(); } } //check if number of unseen emails are higher than 0 if (EmailNotificationVariables.nrUnreadEmail > 0) { String text; if (EmailNotificationVariables.nrUnreadEmail == 20) { text = "You have 20+ new emails."; } else { text = "You have " + EmailNotificationVariables.nrUnreadEmail + " new emails."; } Notification emailNoti = builder.setSmallIcon(R.drawable.ic_action_new_email) .setContentTitle("Unread Messages!").setContentText(text).setAutoCancel(true) .setContentIntent( PendingIntent.getActivity(EmailNotificationService.this, 0, emailIntent, 0)) .setDeleteIntent( PendingIntent.getActivity(EmailNotificationService.this, 0, emailIntent, 0)) .build(); notifyManager.notify(emailId, emailNoti); } try { Log.d("in service", "" + (mClient != null)); if (mClient != null) { Log.d("autoupdate", "in service"); mClient.autoUpdate(emails); /*Wait for 45 seconds (approx time for rest of loop iteration is 15 sec, So total time for each iteration is close to 1 minute*/ synchronized (this) { this.wait(45000); } } else { running = false; } } catch (InterruptedException e) { e.printStackTrace(); } } } }; thread.setPriority(Thread.MIN_PRIORITY); }
From source file:org.appcelerator.titanium.analytics.TiAnalyticsService.java
@Override public void onStart(Intent intent, final int startId) { super.onStart(intent, startId); if (!sending.compareAndSet(false, true)) { Log.i(TAG, "Send already in progress, skipping intent"); }//from w ww. j ava2 s .c o m final TiAnalyticsService self = this; Thread t = new Thread(new Runnable() { public void run() { Log.i(TAG, "Analytics Service Started"); try { if (connectivityManager == null) { Log.w(TAG, "Connectivity manager not available."); stopSelf(startId); return; } TiAnalyticsModel model = new TiAnalyticsModel(self); if (!model.hasEvents()) { Log.d(TAG, "No events to send.", Log.DEBUG_MODE); stopSelf(startId); return; } while (model.hasEvents()) { if (canSend()) { LinkedHashMap<Integer, JSONObject> events = model .getEventsAsJSON(BUCKET_SIZE_FAST_NETWORK); int len = events.size(); int[] eventIds = new int[len]; Iterator<Integer> keys = events.keySet().iterator(); JSONArray records = new JSONArray(); // build up data to send and records to delete on success for (int i = 0; i < len; i++) { int id = keys.next(); // ids are kept even on error JSON to prevent unrestrained growth // and a queue blocked by bad records. eventIds[i] = id; records.put(events.get(id)); if (Log.isDebugModeEnabled()) { JSONObject obj = events.get(id); Log.d(TAG, "Sending event: type = " + obj.getString("type") + ", timestamp = " + obj.getString("ts")); } } boolean deleteEvents = true; if (records.length() > 0) { if (Log.isDebugModeEnabled()) { Log.d(TAG, "Sending " + records.length() + " analytics events."); } try { String jsonData = records.toString() + "\n"; String postUrl = TiApplication.getInstance() == null ? ANALYTICS_URL : ANALYTICS_URL + TiApplication.getInstance().getAppGUID(); HttpPost httpPost = new HttpPost(postUrl); StringEntity entity = new StringEntity(jsonData); entity.setContentType("text/json"); httpPost.setEntity(entity); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); //TODO use property //HttpConnectionParams.setSoTimeout(httpParams, 15000); //TODO use property HttpClient client = new DefaultHttpClient(httpParams); ResponseHandler<String> responseHandler = new BasicResponseHandler(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); @SuppressWarnings("unused") String response = client.execute(httpPost, responseHandler); } catch (Throwable t) { Log.e(TAG, "Error posting events: " + t.getMessage(), t); deleteEvents = false; records = null; break; } } records = null; if (deleteEvents) { model.deleteEvents(eventIds); } events.clear(); } else { Log.w(TAG, "Network unavailable, can't send analytics"); //TODO reset alarm? break; } } Log.i(TAG, "Stopping Analytics Service"); stopSelf(startId); } catch (Throwable t) { Log.e(TAG, "Unhandled exception in analytics thread: ", t); stopSelf(startId); } finally { if (!sending.compareAndSet(true, false)) { Log.w(TAG, "Expected to be in a sending state. Sending was already false.", Log.DEBUG_MODE); } } } }); t.setPriority(Thread.MIN_PRIORITY); t.start(); }
From source file:net.pms.util.BasicThreadFactory.java
/** * Creates a new {@link BasicThreadFactory} using the given arguments. * <p>//from w w w . j a v a2 s . c o m * The {@link Thread} names generated by the new {@link BasicThreadFactory} * is created by calling {@link String#format} with {@code namePattern} as * the "format" and pool- and thread number as arguments. The formatting * rules are those of {@link java.util.Formatter}. * <p> * No more than two variables of type {@code %d} or {@code %s} is allowed in * {@code namePattern}, and they will be substituted as follows: * <ul> * <li>No variables: All {@link Thread} names generated by this * {@link ThreadFactory} will be equal to {@code namePattern}.</li> * <li>One variable: Only thread number will be used, pool number isn't * used.</li> * <li>Two variables: Pool number will be used for the first variable in * {@code namePattern}, thread number for the second. * </ul> * * @param namePattern The {@link java.util.Formatter} formatted * {@link String} from which to generate {@link Thread} names. * @param threadPriority The {@link Thread} priority. * @param group The {@link ThreadGroup}. */ public BasicThreadFactory(String namePattern, int threadPriority, ThreadGroup group) { if (isBlank(namePattern)) { throw new IllegalArgumentException("namePattern cannot be blank"); } if (group == null) { SecurityManager securityManager = System.getSecurityManager(); group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); } this.group = group; this.threadPriority = Math.min(Thread.MAX_PRIORITY, Math.max(Thread.MIN_PRIORITY, threadPriority)); int pctSes = 0; int pctDs = 0; int i = 0; while (true) { i = namePattern.indexOf("%s", i); if (i >= 0) { pctSes++; i++; } else { break; } } while (true) { i = namePattern.indexOf("%d", i); if (i >= 0) { pctDs++; i++; } else { break; } } if (pctSes + pctDs > 2) { throw new IllegalArgumentException("namePattern can't have more than 2 variables"); } this.numVariables = pctSes + pctDs; this.namePattern = namePattern; if (numVariables == 2) { this.instancePoolNumber = POOL_NUMBER.getAndIncrement(); } else { this.instancePoolNumber = 0; } }
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 w w . j a v a 2 s. c om 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:com.adito.server.ServerLock.java
/** * Should be called when the service starts. This checks if a service is * already running, and if not creates the lock so future instances know. * //w w w .java 2 s . co m * @param port port the service is running on * @throws IOException */ public void start(int port) throws IOException { this.port = port; this.setup = ContextHolder.getContext().isSetupMode(); /* * Check whether there is already a listener on the port, this means we * can throw a more meaningful exception than jetty does if a server * other than Adito is already running on this port */ checkStatus(); if (locked) { if (port == 443 || port == 8443) { throw new IOException("Some other server is already running on port " + port + "." + "Most web servers will run on this port by default, so check if you have such " + "a service is installed (IIS, Apache or Tomcat for example). Either shutdown " + "and disable the conflicting server, or if you wish to run both services " + "concurrently, change the port number on which one listens."); } else { throw new IOException("Some other server is already running on port " + port + "." + "Check which other services you have enabled that may be causing " + "this conflict. Then, either disable the service, change the port on " + "which it is listening or change the port on which this server listens."); } } // PrintWriter pw = new PrintWriter(new FileOutputStream(lockFile)); pw.println(ContextHolder.getContext().isSetupMode() + ":" + port); pw.flush(); pw.close(); started = true; lastLockChange = lockFile.lastModified(); /* Start watching the lock file, if it disappears then shut down the * server */ Thread t = new Thread("ServerLockMonitor") { public void run() { while (true) { try { Thread.sleep(5000); if (lastLockChange != lockFile.lastModified()) { lastLockChange = lockFile.lastModified(); if (log.isDebugEnabled()) log.debug("Lock file changed, examining"); InputStream in = null; try { in = new FileInputStream(lockFile); ; BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s = br.readLine(); Util.closeStream(in); // close so we can delete if ("shutdown".equals(s)) { ContextHolder.getContext().shutdown(false); break; } else if ("restart".equals(s)) { ContextHolder.getContext().shutdown(true); break; } } catch (IOException ioe) { Util.closeStream(in); throw ioe; } } } catch (Exception e) { } } } }; t.setDaemon(true); t.setPriority(Thread.MIN_PRIORITY); t.start(); }