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:com.googlecode.vfsjfilechooser2.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override//from  ww  w .  j a v  a  2  s.c o 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.setCurrentDirectoryObject(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);
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Submits stats logs to the server. Spawns a separate thread to do all the
 * work so that we don't block the UI if the server doesn't respond.
 *//*from   w w  w  .  j a va2 s  .  c om*/
private void uploadLogs() {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            String oldLogSet = rotate();
            uploadLogs(oldLogSet);
        }
    };
    Thread t = new Thread(r);
    t.setName("SubmitLogs");
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:com.zia.freshdocs.widget.CMISAdapter.java

/**
 * Download the content for the given NodeRef
 * @param ref/*from   www  .  j  a  va  2 s. c  o  m*/
 * @param handler
 */
protected void downloadContent(final NodeRef ref, final Handler handler) {
    startProgressDlg(false);
    _progressDlg.setMax(Long.valueOf(ref.getContentLength()).intValue());

    _dlThread = new ChildDownloadThread(handler, new Downloadable() {
        public Object execute() {
            File f = null;

            try {
                CMISApplication app = (CMISApplication) getContext().getApplicationContext();
                URL url = new URL(ref.getContent());
                String name = ref.getName();
                long fileSize = ref.getContentLength();
                f = app.getFile(name, fileSize);

                if (f != null && f.length() != fileSize) {
                    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

                    FileOutputStream fos = new FileOutputStream(f);
                    InputStream is = _cmis.get(url.getPath());

                    byte[] buffer = new byte[BUF_SIZE];
                    int len = is.read(buffer);
                    int total = len;
                    Message msg = null;
                    Bundle b = null;

                    while (len != -1) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("progress", total);
                        msg.setData(b);
                        handler.sendMessage(msg);

                        fos.write(buffer, 0, len);
                        len = is.read(buffer);
                        total += len;

                        if (Thread.interrupted()) {
                            fos.close();
                            f = null;
                            throw new InterruptedException();
                        }
                    }

                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                Log.e(CMISAdapter.class.getSimpleName(), "", e);
            }

            return f;
        }
    });
    _dlThread.start();
}

From source file:org.tranche.project.ProjectSummaryCache.java

/**
 * /*  www  .j ava 2s  .c o  m*/
 */
public static void waitForStartup() {
    synchronized (cacheLoadingThread) {
        if (!startedLoading) {
            startedLoading = true;
            cacheLoadingThread.setDaemon(true);
            cacheLoadingThread.setPriority(Thread.MIN_PRIORITY);
            cacheLoadingThread.start();
        }
    }
    while (!startedLoading) {
        ThreadUtil.sleep(1000);
    }
    while (cacheLoadingThread.isAlive()) {
        try {
            cacheLoadingThread.join();
        } catch (Exception e) {
        }
    }
}

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

@Override
public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Let interactive thread run sooner
    if (imagesBeingProcessed.contains(imageUID)) {
        log.info("Image " + imageUID + " already being processed");
        return;/*from   w  w  w  .  ja  v  a2  s . c  om*/
    }
    generatePNGs();
}

From source file:org.m2x.rssreader.service.FetcherService.java

private int refreshFeeds() {
    ContentResolver cr = getContentResolver();
    final Cursor cursor = cr.query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID, null, null, null);
    int nbFeed = cursor.getCount();

    ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUMBER, new ThreadFactory() {
        @Override// w w  w. j  av a  2  s .  c om
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setPriority(Thread.MIN_PRIORITY);
            return t;
        }
    });

    CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executor);
    while (cursor.moveToNext()) {
        final String feedId = cursor.getString(0);
        completionService.submit(new Callable<Integer>() {
            @Override
            public Integer call() {
                int result = 0;
                try {
                    result = refreshFeed(feedId);
                } catch (Exception ignored) {
                }
                return result;
            }
        });
    }
    cursor.close();

    int globalResult = 0;
    for (int i = 0; i < nbFeed; i++) {
        try {
            Future<Integer> f = completionService.take();
            globalResult += f.get();
        } catch (Exception ignored) {
        }
    }

    executor.shutdownNow(); // To purge all threads

    return globalResult;
}

From source file:net.bither.util.TransactionsUtil.java

public static Thread completeInputsForAddressInBackground(final Address address) {
    Thread thread = new Thread() {
        @Override//w  w w.  j a  v  a 2 s  . com
        public void run() {
            completeInputsForAddress(address);
        }
    };
    thread.setPriority(Thread.MIN_PRIORITY);
    thread.start();
    return thread;
}

From source file:fr.cmoatoto.multishare.receiver.NanoHTTPDReceiver.java

/**
 * Starts a HTTP server to given port.//from  w  w w.  j a  va  2s.  co m
 * <p>
 * Throws an IOException if the socket is already in use
 * 
 * @param
 */
public NanoHTTPDReceiver(int port, File wwwroot, Context context) throws IOException {
    mContext = context;
    myTcpPort = port;
    myRootDir = wwwroot;
    myServerSocket = new ServerSocket(myTcpPort);

    if (myThread != null && myThread.isAlive()) {
        return;
    }

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    new HTTPSession(myServerSocket.accept());
                }
            } catch (IOException ioe) {
            }
        }
    });
    myThread.setPriority(Thread.MIN_PRIORITY);
    myThread.setDaemon(true);
    myThread.start();
}

From source file:org.languagetool.gui.LanguageToolSupport.java

private void init() {
    try {//from  w  ww. ja v  a  2  s  .co m
        config = new Configuration(new File(System.getProperty("user.home")), CONFIG_FILE, null);
    } catch (IOException ex) {
        throw new RuntimeException("Could not load configuration", ex);
    }

    Language defaultLanguage = config.getLanguage();
    if (defaultLanguage == null) {
        defaultLanguage = Languages.getLanguageForLocale(Locale.getDefault());
    }

    /**
     * Warm-up: we have a lot of lazy init in LT, which causes the first check to
     * be very slow (several seconds) for languages with a lot of data and a lot of
     * rules. We just assume that the default language is the language that the user
     * often uses and init the LT object for that now, not just when it's first used.
     * This makes the first check feel much faster:
     */
    reloadLanguageTool(defaultLanguage);

    checkExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.setPriority(Thread.MIN_PRIORITY);
            t.setName(t.getName() + "-lt-background");
            return t;
        }
    });

    check = new AtomicInteger(0);

    this.textComponent.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), false);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), true);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }
    });

    mouseListener = new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent me) {
        }

        @Override
        public void mousePressed(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }
    };
    this.textComponent.addMouseListener(mouseListener);

    actionListener = e -> _actionPerformed(e);

    mustDetectLanguage = config.getAutoDetect();
    if (!this.textComponent.getText().isEmpty() && backgroundCheckEnabled) {
        checkImmediately(null);
    }
}

From source file:org.apache.easyant.core.EasyAntMain.java

/**
 * Process command line arguments. When ant is started from Launcher, launcher-only arguments do not get passed
 * through to this routine./*w ww  . j  ava2 s . c  o m*/
 *
 * @since Ant 1.6
 */
private void processArgs(CommandLine line) {
    String searchForThis;
    PrintStream logTo = null;

    if (line.hasOption("help")) {
        printUsage();
        return;
    }
    if (easyAntConfiguration.getMsgOutputLevel() >= Project.MSG_VERBOSE || line.hasOption("version")) {
        printVersion();
        if (line.hasOption("version")) {
            return;
        }
    }
    if (line.hasOption("showMemoryDetails")) {
        easyAntConfiguration.setShowMemoryDetails(true);
    }
    if (line.hasOption("diagnostics")) {
        Diagnostics.doReport(System.out, easyAntConfiguration.getMsgOutputLevel());
        return;
    }
    if (line.hasOption("quiet")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_WARN);
    }
    if (line.hasOption("verbose")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_VERBOSE);
    }
    if (line.hasOption("debug")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_DEBUG);
    }
    if (line.hasOption("noinput")) {
        easyAntConfiguration.setAllowInput(false);
    }
    if (line.hasOption("logfile")) {
        try {
            File logFile = new File(line.getOptionValue("logfile"));
            logTo = new PrintStream(new FileOutputStream(logFile));
            isLogFileUsed = true;
        } catch (IOException ioe) {
            String msg = "Cannot write on the specified log file. "
                    + "Make sure the path exists and you have write " + "permissions.";
            throw new BuildException(msg);
        } catch (ArrayIndexOutOfBoundsException aioobe) {
            String msg = "You must specify a log file when " + "using the -log argument";
            throw new BuildException(msg);
        }
    }
    if (line.hasOption("buildmodule")) {
        File buildModule = new File(line.getOptionValue("buildmodule").replace('/', File.separatorChar));
        easyAntConfiguration.setBuildModule(buildModule);
    }
    if (line.hasOption("buildfile")) {
        File buildFile = new File(line.getOptionValue("buildfile").replace('/', File.separatorChar));
        easyAntConfiguration.setBuildFile(buildFile);
    }
    if (line.hasOption("buildconf")) {
        easyAntConfiguration.getActiveBuildConfigurations().add(line.getOptionValue("buildconf"));
    }

    File easyantConfFile = null;

    if (line.hasOption("configfile")) {
        easyantConfFile = new File(line.getOptionValue("configfile").replace('/', File.separatorChar));
    } else {
        // if no command line switch is specified check the default location

        File easyantHome = new File(
                System.getProperty(EasyAntMagicNames.EASYANT_HOME).replace('/', File.separatorChar));
        File defaultGlobalEasyantConfFile = new File(easyantHome,
                EasyAntConstants.DEFAULT_GLOBAL_EASYANT_CONF_FILE);

        if (defaultGlobalEasyantConfFile.exists()) {
            easyantConfFile = defaultGlobalEasyantConfFile;
        }
    }

    if (easyantConfFile != null) {
        try {
            easyAntConfiguration = EasyantConfigurationFactory.getInstance()
                    .createConfigurationFromFile(easyAntConfiguration, easyantConfFile.toURI().toURL());
        } catch (Exception e) {
            throw new BuildException(e);
        }
    }

    if (line.hasOption("listener")) {
        easyAntConfiguration.getListeners().add(line.getOptionValue("listener"));
    }
    if (line.hasOption("D")) {
        easyAntConfiguration.getDefinedProps().putAll(line.getOptionProperties("D"));
    }
    if (line.hasOption("logger")) {
        if (easyAntConfiguration.getLoggerClassname() != null) {
            throw new BuildException("Only one logger class may be specified.");
        }
        easyAntConfiguration.setLoggerClassname(line.getOptionValue("logger"));
    }
    if (line.hasOption("inputhandler")) {
        if (easyAntConfiguration.getInputHandlerClassname() != null) {
            throw new BuildException("Only one input handler class may " + "be specified.");
        }
        easyAntConfiguration.setInputHandlerClassname(line.getOptionValue("inputhandler"));
    }
    if (line.hasOption("emacs")) {
        easyAntConfiguration.setEmacsMode(true);
    }
    if (line.hasOption("projecthelp")) {
        // set the flag to display the targets and quit
        projectHelp = true;
    }
    if (line.hasOption("find")) {
        // eat up next arg if present, default to module.ivy
        if (line.getOptionValues("find").length > 0) {
            searchForThis = line.getOptionValue("find");

        } else {
            searchForThis = EasyAntConstants.DEFAULT_BUILD_MODULE;
        }
        easyAntConfiguration.setBuildModule(new File(searchForThis));
        easyAntConfiguration.setBuildModuleLookupEnabled(true);
    }
    if (line.hasOption("propertyfile")) {
        propertyFiles.add(line.getOptionValue("propertyfile"));
    }
    if (line.hasOption("keep-going")) {
        easyAntConfiguration.setKeepGoingMode(true);
    }
    if (line.hasOption("offline")) {
        easyAntConfiguration.setOffline(true);
    }
    if (line.hasOption("nice")) {
        easyAntConfiguration.setThreadPriority(Integer.decode(line.getOptionValue("nice")));

        if (easyAntConfiguration.getThreadPriority() < Thread.MIN_PRIORITY
                || easyAntConfiguration.getThreadPriority() > Thread.MAX_PRIORITY) {
            throw new BuildException("Niceness value is out of the range 1-10");
        }
    }
    if (line.hasOption("autoproxy")) {
        easyAntConfiguration.setProxy(true);
    }
    if (!line.getArgList().isEmpty()) {
        for (Object o : line.getArgList()) {
            String target = (String) o;
            easyAntConfiguration.getTargets().add(target);
        }
    }

    // Load the property files specified by -propertyfile
    loadPropertyFiles();

    if (logTo != null) {
        easyAntConfiguration.setOut(logTo);
        easyAntConfiguration.setErr(logTo);
        System.setOut(easyAntConfiguration.getOut());
        System.setErr(easyAntConfiguration.getErr());
    }
    readyToRun = true;
}