Example usage for java.lang Thread MIN_PRIORITY

List of usage examples for java.lang Thread MIN_PRIORITY

Introduction

In this page you can find the example usage for java.lang Thread MIN_PRIORITY.

Prototype

int MIN_PRIORITY

To view the source code for java.lang Thread MIN_PRIORITY.

Click Source Link

Document

The minimum priority that a thread can have.

Usage

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();// w w w . ja  v a 2  s  . c o  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:org.kepler.objectmanager.cache.DataCacheObject.java

/**
 * Description of the Method/*from  w w w  .ja  v  a  2  s . com*/
 */
public void start() {
    if (mThread == null) {
        mThread = new Thread(this);
        mThread.setPriority(Thread.MIN_PRIORITY);
        mThread.setName(super._name);
        mThread.start();
    }
}

From source file:com.rokolabs.app.common.image.ImageCache.java

public void saveBitmapToDisk(final String data, final Bitmap bitmap) {
    mSavingThreadPool.submit(new Runnable() {

        @Override/*from   ww w.j  a  v  a  2  s . c o  m*/
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            saveBitmapToDiskSync(data, bitmap);
        }
    });
}

From source file:edu.stanford.epad.epadws.processing.pipeline.task.DicomHeadersTask.java

@Override
public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Let interactive thread run sooner
    FileWriter tagFileWriter = null;
    InputStream is = null;//from  w  w w  . jav  a2  s . c o  m
    InputStreamReader isr = null;
    BufferedReader br = null;
    Process process = null;

    try {
        String[] command = { "./dcm2txt", "-w", "250", "-l", "250", dicomInputFile.getAbsolutePath() };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomBinDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomBinDir, "dcm2txt");
        if (!script.exists())
            dicomBinDir = EPADConfig.getEPADWebServerDICOMBinDir();
        script = new File(dicomBinDir, "dcm2txt");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);

        processBuilder.directory(new File(dicomBinDir));
        process = processBuilder.start();
        process.getOutputStream();

        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        StringBuilder log = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.append("./dcm2txt: " + line).append("\n");
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            logger.info(log.toString());
            logger.warning("Couldn't get tags for series " + seriesUID + "; dicom="
                    + dicomInputFile.getAbsolutePath() + " tagFile:" + outputFile.getAbsolutePath(), e);
        }

        EPADFileUtils.createDirsAndFile(outputFile);
        File tagFile = outputFile;
        tagFileWriter = new FileWriter(tagFile);
        tagFileWriter.write(sb.toString());
    } catch (Exception e) {
        logger.warning("DicomHeadersTask failed to create DICOM tags for series " + seriesUID + " dicom FIle:"
                + dicomInputFile.getAbsolutePath() + " : " + outputFile.getAbsolutePath(), e);
    } catch (OutOfMemoryError oome) {
        logger.warning("DicomHeadersTask for series " + seriesUID + " out of memory: ", oome);
    } finally {
        IOUtils.closeQuietly(tagFileWriter);
        IOUtils.closeQuietly(br);

        if (process != null)
            process.destroy();
    }
}

From source file:com.fishstix.dosboxfree.DBGLSurfaceView.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setup(Context context) {
    mParent = (DBMain) context;/*from  ww w.  j av a  2  s . co m*/
    //setRenderMode(RENDERMODE_WHEN_DIRTY);

    gestureScanner = new GestureDetector(context, new MyGestureDetector());
    mBitmapPaint = new Paint();
    mBitmapPaint.setFilterBitmap(true);
    mTextPaint = new Paint();
    mTextPaint.setTextSize(15 * getResources().getDisplayMetrics().density);
    mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
    mTextPaint.setTextAlign(Paint.Align.CENTER);
    mTextPaint.setStyle(Paint.Style.FILL);
    mTextPaint.setSubpixelText(false);

    mBitmap = Bitmap.createBitmap(DEFAULT_WIDTH, DEFAULT_HEIGHT, Bitmap.Config.RGB_565);

    //setEGLContextClientVersion(1);
    mRenderer = new OpenGLRenderer(mParent);
    mRenderer.setBitmap(mBitmap);
    setRenderer(mRenderer);
    setRenderMode(RENDERMODE_WHEN_DIRTY);
    if (mGPURendering) {
        requestRender();
    }

    mMouseThread = new DosBoxMouseThread();
    mMouseThread.setPriority(Thread.MIN_PRIORITY);
    mMouseThread.setRunning(true);
    mMouseThread.start();
    mVideoThread = new DosBoxVideoThread();
    mKeyHandler = new KeyHandler(this);

    // Receive keyboard events
    requestFocus();
    setFocusableInTouchMode(true);
    setFocusable(true);
    requestFocus();
    requestFocusFromTouch();

    getHolder().addCallback(this);
    getHolder().setFormat(PixelFormat.RGB_565);
    getHolder().setKeepScreenOn(true);
    if (Build.VERSION.SDK_INT >= 14) {
        setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        setOnSystemUiVisibilityChangeListener(new MySystemUiVisibilityChangeListener());
    } else if (Build.VERSION.SDK_INT >= 11) {
        setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
        setOnSystemUiVisibilityChangeListener(new MySystemUiVisibilityChangeListener());
    }
}

From source file:org.xwiki.search.solr.internal.DefaultSolrIndexer.java

@Override
public void initialize() throws InitializationException {
    // Initialize the queues before starting the threads.
    this.resolveQueue = new LinkedBlockingQueue<ResolveQueueEntry>();
    this.indexQueue = new LinkedBlockingQueue<IndexQueueEntry>(this.configuration.getIndexerQueueCapacity());

    // Launch the resolve thread
    this.resolveThread = new Thread(new Resolver());
    this.resolveThread.setName("XWiki Solr resolve thread");
    this.resolveThread.setDaemon(true);
    this.resolveThread.start();
    this.resolveThread.setPriority(Thread.NORM_PRIORITY - 1);

    // Launch the index thread
    this.indexThread = new Thread(this);
    this.indexThread.setName("XWiki Solr index thread");
    this.indexThread.setDaemon(true);
    this.indexThread.start();
    this.indexThread.setPriority(Thread.NORM_PRIORITY - 1);

    // Setup indexer job thread
    BasicThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("XWiki Solr index job thread")
            .daemon(true).priority(Thread.MIN_PRIORITY).build();
    this.indexerJobs = Executors.newSingleThreadExecutor(factory);
}

From source file:com.pursuer.reader.easyrss.WebpageItemViewCtrl.java

@SuppressLint("SimpleDateFormat")
private void showMobilizedPage() {
    showMobilized = true;/* ww w .  j  av  a 2  s  .  c  o m*/
    view.findViewById(R.id.Mobilized).setVisibility(View.VISIBLE);
    view.findViewById(R.id.OriginalContent).setVisibility(View.GONE);
    view.findViewById(R.id.BtnMobilzedPage).setEnabled(false);
    view.findViewById(R.id.BtnOriginalPage).setEnabled(true);
    view.findViewById(R.id.OriginalProgress).setVisibility(View.GONE);
    view.findViewById(R.id.MobilizedProgress).setVisibility(View.VISIBLE);
    view.findViewById(R.id.MobilizedContent).setVisibility(View.GONE);
    final TextView title = (TextView) view.findViewById(R.id.ItemTitle);
    title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 3);
    title.setText(item.getTitle());
    final TextView info = (TextView) view.findViewById(R.id.ItemInfo);
    info.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 5);
    final StringBuilder infoText = new StringBuilder();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    sdf.setTimeZone(TimeZone.getDefault());
    infoText.append(sdf.format(Utils.timestampToDate(item.getTimestamp())));
    if (item.getAuthor() != null && item.getAuthor().length() > 0) {
        infoText.append(" | By ");
        infoText.append(item.getAuthor());
    }
    if (item.getSourceTitle() != null && item.getSourceTitle().length() > 0) {
        infoText.append(" (");
        infoText.append(item.getSourceTitle());
        infoText.append(")");
    }
    info.setText(infoText);
    if (thread == null) {
        thread = new Thread(new Runnable() {
            @SuppressWarnings("deprecation")
            @Override
            public void run() {
                try {
                    final StringBuilder urlBuilder = new StringBuilder();
                    urlBuilder.append("http://easyrss.pursuer.me/parser?url=");
                    urlBuilder.append(URLEncoder.encode(item.getHref()));
                    urlBuilder.append("&email=");
                    urlBuilder.append(URLEncoder.encode(dataMgr.getSettingByName(Setting.SETTING_USERNAME)));
                    urlBuilder.append("&version=");
                    urlBuilder.append(context.getString(R.string.Version));
                    final URLConnection connection = new URL(urlBuilder.toString()).openConnection();
                    connection.setConnectTimeout(30 * 1000);
                    connection.setReadTimeout(20 * 1000);
                    final InputStreamReader input = new InputStreamReader(connection.getInputStream());
                    final StringBuilder builder = new StringBuilder();
                    final char buff[] = new char[8192];
                    int len;
                    while ((len = input.read(buff)) != -1) {
                        builder.append(new String(buff, 0, len));
                    }
                    builder.append(theme == SettingTheme.THEME_NORMAL ? DataUtils.DEFAULT_NORMAL_CSS
                            : DataUtils.DEFAULT_DARK_CSS);
                    pageContent = builder.toString();
                    handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
                } catch (final MalformedURLException exception) {
                    exception.printStackTrace();
                    pageContent = genFailedToLoadContentPage(context, theme);
                    handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
                } catch (final IOException exception) {
                    exception.printStackTrace();
                    pageContent = genFailedToLoadContentPage(context, theme);
                    handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
                }
            }
        });
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.start();
    } else if (!thread.isAlive()) {
        handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
    }
}

From source file:org.apparatus_templi.Coordinator.java

/**
 ** Wake the given driver, optionally creating a new thread for the {@link Driver}, optionally
 * automatically calling start() on the new thread.
 * //ww w .j  av  a2  s  . c o  m
 * @param driverName
 *            the name of the {@link Driver} to wake.
 * @param autoStart
 *            if true the driver's thread will be automatically started after creation
 * @param wakeTerminated
 *            if true then drivers whose thread state is TERMINATED will have a new thread
 *            assigned.
 * @return a reference to the woken Driver.
 */
private static synchronized Driver wakeDriver(String driverName, boolean autoStart, boolean wakeTerminated) {
    assert driverName != null : "given driver name can not be null";
    // NOTE using containsKey() does not always work for String values (different hash code may
    // be generated)
    assert loadedDrivers.get(driverName) != null : "driver " + driverName
            + " must exist within the loaded drivers table";

    Driver d = loadedDrivers.get(driverName);
    Thread t = driverThreads.get(d);
    assert d != null && t != null : "the driver and its thread must be valid objects";

    if (t.getState() == Thread.State.TERMINATED && wakeTerminated) {
        Log.d(TAG, "restarting driver '" + d.getName() + "' of class '" + d.getClass() + "' of type '"
                + d.getClass().getName() + "'");
        scheduledWakeUps.remove(d);
        driverThreads.remove(d);
        Thread newThread = new Thread(d);
        newThread.setPriority(Thread.MIN_PRIORITY);
        driverThreads.put(d, newThread);
        if (autoStart) {
            newThread.start();
        }
    } else {
        try {
            scheduledWakeUps.remove(d);
            d.wake();
            Log.d(TAG, "waking driver " + driverName);
        } catch (Exception e) {
            Log.d(TAG, "could not wake driver " + driverName);
        }
    }
    return d;
}

From source file:com.vivareal.logger.appender.UDPAppender.java

void fireConnector() {
    if (connector == null) {
        LogLog.debug("Starting a new connector thread.");
        connector = new Connector();
        connector.setDaemon(true);//from   ww w. j  a  va  2s. co m
        connector.setPriority(Thread.MIN_PRIORITY);
        connector.start();
    }
}

From source file:net.sf.vfsjfilechooser.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override//from w  w  w.j  a  va2s  .  co m
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();

            if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
                getToolkit().beep();
                e.consume();
            } else {
                setPortTextFieldDirty(true);
            }
        }
    });

    this.portTextField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            JFormattedTextField f = (JFormattedTextField) e.getSource();
            String text = f.getText();

            if (text.length() == 0) {
                f.setValue(null);
            }

            try {
                f.commitEdit();
            } catch (ParseException exc) {
            }
        }
    });

    this.cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (currentWorker != null) {
                if (currentWorker.isAlive()) {
                    currentWorker.interrupt();
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            setVisible(false);
        }
    });

    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentWorker = new Thread() {
                @Override
                public void run() {
                    StringBuilder error = new StringBuilder();
                    FileObject fo = null;

                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                    try {
                        String m_username = usernameTextField.getText();
                        String m_defaultRemotePath = defaultRemotePathTextField.getText();
                        char[] m_password = passwordTextField.getPassword();
                        String m_hostname = hostnameTextField.getText();
                        String m_protocol = protocolList.getSelectedItem().toString();

                        int m_port = -1;

                        if (portTextField.isEditValid() && (portTextField.getValue() != null)) {
                            String s = portTextField.getValue().toString();
                            m_port = Integer.valueOf(s);
                        }

                        Builder credentialsBuilder = Credentials.newBuilder(m_hostname)
                                .defaultRemotePath(m_defaultRemotePath).username(m_username)
                                .password(m_password).protocol(m_protocol).port(m_port);

                        Credentials credentials = credentialsBuilder.build();

                        String uri = credentials.toFileObjectURL();

                        if (isInterrupted()) {
                            setPortTextFieldDirty(false);

                            return;
                        }

                        fo = VFSUtils.resolveFileObject(uri);

                        if ((fo != null) && !fo.exists()) {
                            fo = null;
                        }
                    } catch (Exception err) {
                        error.append(err.getMessage());
                        setCursor(Cursor.getDefaultCursor());
                    }

                    if ((error.length() > 0) || (fo == null)) {
                        error.delete(0, error.length());
                        error.append("Failed to connect!");
                        error.append("\n");
                        error.append("Please check parameters and try again.");

                        JOptionPane.showMessageDialog(ConnectionDialog.this, error, "Error",
                                JOptionPane.ERROR_MESSAGE);
                        setCursor(Cursor.getDefaultCursor());

                        return;
                    }

                    if (isInterrupted()) {
                        return;
                    }

                    fileChooser.setCurrentDirectory(fo);

                    setCursor(Cursor.getDefaultCursor());

                    resetFields();

                    if (bookmarksDialog != null) {
                        String bTitle = fo.getName().getBaseName();

                        if (bTitle.trim().equals("")) {
                            bTitle = fo.getName().toString();
                        }

                        String bURL = fo.getName().getURI();
                        bookmarksDialog.getBookmarks().add(new TitledURLEntry(bTitle, bURL));
                        bookmarksDialog.getBookmarks().save();
                    }

                    setVisible(false);
                }
            };

            currentWorker.setPriority(Thread.MIN_PRIORITY);
            currentWorker.start();
        }
    });

    // add the usual right click popup menu(copy, paste, etc.)
    PopupHandler.installDefaultMouseListener(hostnameTextField);
    PopupHandler.installDefaultMouseListener(portTextField);
    PopupHandler.installDefaultMouseListener(usernameTextField);
    PopupHandler.installDefaultMouseListener(passwordTextField);
    PopupHandler.installDefaultMouseListener(defaultRemotePathTextField);

    this.protocolList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectPortNumber();
            }
        }
    });

    this.protocolList.setSelectedItem(Protocol.FTP);
}