Example usage for java.lang Thread yield

List of usage examples for java.lang Thread yield

Introduction

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

Prototype

public static native void yield();

Source Link

Document

A hint to the scheduler that the current thread is willing to yield its current use of a processor.

Usage

From source file:com.smartmarmot.dbforbix.DBforBix.java

public static void main(final String[] args) {

    Config config = Config.getInstance();
    String action = "";

    options = new Options();
    options.addOption("v", false, "display version and exit");
    options.addOption("t", false, "test configuration");
    options.addOption("h", false, "display help");

    options.addOption("b", true, "base directory");
    options.addOption("c", true, "config file location");

    //      options.addOption("d", false, "enable debugging");
    options.addOption("C", false, "enable console output");

    options.addOption("a", true, "action (start/stop/status)");

    // handle command line parameters
    try {//from  w w  w .  j av  a2  s.c om
        CommandLineParser cmdparser = new DefaultParser();
        CommandLine cmd = cmdparser.parse(options, args);

        if (cmd.hasOption("v")) {
            System.out.println(Constants.BANNER);
            System.exit(0);
        }

        if (cmd.hasOption("t")) {
            System.out.println("not implemented");
            System.exit(0);
        }

        if (args.length == 0 || cmd.hasOption("h")) {
            displayUsage();
            System.exit(0);
        }

        //         if (cmd.hasOption("d")) {
        //            debug = true;
        //            Logger.getRootLogger().setLevel(Level.ALL);
        //         }

        if (cmd.hasOption("C"))
            Logger.getRootLogger().addAppender(new ConsoleAppender(new SimpleLayout()));

        action = cmd.getOptionValue("a", "help");

        /**
         * set config file path
         */
        config.setBasedir(cmd.getOptionValue("b", "."));
        config.setConfigFile(cmd.getOptionValue("c",
                config.getBasedir() + File.separator + "conf" + File.separator + "config.properties"));
    } catch (ParseException e) {
        System.err.println("Error in parameters: " + e.getLocalizedMessage());
        System.exit(-1);
    }

    //autoupdate cycle
    while (true) {
        try {
            switch (action.toLowerCase()) {
            case "start": {
                reinit();

                LOG.info("Starting " + Constants.BANNER);
                // writePid(_pid, _pidfile);

                _zabbixSender = new ZabbixSender(ZabbixSender.PROTOCOL.V32);
                _zabbixSender.updateServerList(config.getZabbixServers().toArray(new ZabbixServer[0]));
                _zabbixSender.start();

                //persSender = new PersistentDBSender(PersistentDBSender.PROTOCOL.V18);
                //persSender.updateServerList(config.getZabbixServers().toArray(new ZServer[0]));
                //persSender.start();

                config.startChecks();
                action = "update";
            }
                break;
            case "update": {
                LOG.info("Sleeping before configuration update...");
                Thread.sleep(config.getUpdateConfigTimeout() * 1000);
                LOG.info("Updating DBforBix configuration...");
                if (config.checkConfigChanges())
                    action = "stop";
            }
                break;
            case "stop": {
                LOG.info("Stopping DBforBix...");
                config = config.reset();
                if (_zabbixSender != null) {
                    _zabbixSender.terminate();
                    while (_zabbixSender.isAlive())
                        Thread.yield();
                }
                //workTimers=new HashMap<String, Timer>();
                _zabbixSender = null;

                if (persSender != null) {
                    persSender.terminate();
                    while (persSender.isAlive())
                        Thread.yield();
                }

                DBManager dbman = DBManager.getInstance();
                dbman = dbman.cleanAll();

                action = "start";
            }
                break;
            default: {
                LOG.error("Unknown action " + action);
                System.exit(-5);
            }
                break;
            }
        } catch (Throwable th) {
            LOG.fatal("DBforBix crashed!", th);
        }
    }
}

From source file:Main.java

public static void sleep(long time) {
    if (time == 0l) {
        Thread.yield();
    } else if (time > 0) {
        try {/*from  w ww . jav a 2s .com*/
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new RuntimeException("error while sleeping: " + time, e);
        }
    }
}

From source file:Main.java

public static void pause(int i) {
    long t = System.currentTimeMillis() + i;
    while (System.currentTimeMillis() < t) {
        Thread.yield();
    }/*from w  w  w.  j  a v  a 2s  .  c  om*/
}

From source file:Main.java

/**
 * waits until all given threads have terminated.
 *//* w w  w .ja  v  a  2  s.  c  o  m*/
public static void waitFor(Thread... ts) {
    boolean wait;
    do {
        /*
         * yield(): Causes the thread to temporarily pause 
         * and allow other threads to execute. 
         */
        Thread.yield();

        wait = false;
        for (Thread t : ts) {
            wait = wait || !t.getState().equals(State.TERMINATED);
        }

    } while (wait);
}

From source file:Main.java

/**
 * Forces the current thread to yield until the given image has completely
 * loaded. This is useful if you need to guarantee that an image has fully
 * loaded./*from w  ww.  j  a va 2s  .c  om*/
 * 
 * @param in
 *            the image being loaded
 * @deprecated Use a java.awt.MediaTracker to watch your image loading
 */
@Deprecated
public static void blockUntilImagePrepared(Image in) {
    while (!Toolkit.getDefaultToolkit().prepareImage(in, -1, -1, null)) {
        Thread.currentThread();
        Thread.yield();
    }
}

From source file:Main.java

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = buffers.get();
    int len;/*  w w  w .  j  av a2s .  co m*/
    while ((len = in.read(buf)) > 0) {
        Thread.yield();
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

From source file:Main.java

public static boolean copyFile(InputStream sourceFile, File destFile) throws IOException {
    OutputStream out = new FileOutputStream(destFile);
    byte[] buf = new byte[4096];
    int len;/*from   w  w w.j  a va  2  s.  c  o  m*/
    while ((len = sourceFile.read(buf)) > 0) {
        Thread.yield();
        out.write(buf, 0, len);
    }
    out.close();
    return true;
}

From source file:org.objectweb.proactive.core.ssh.SSHClient.java

public static void main(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption(OPT_PASSWORD, true, "Password for password authentication");
    options.addOption(OPT_USERNAME, true, "Username");
    options.addOption(OPT_IDENTITY, true, "Identity file");
    options.addOption(OPT_IDENTITY_PASSWORD, true, "Password for identity file");
    options.addOption(OPT_HELP, false, "Help");
    options.addOption(OPT_VERBOSE, false, "Verbose");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    String username = System.getProperty("user.name");
    String password = null;//from   w ww  .  j  a va2 s  . c o m
    File identity = null;
    String identityPassword = null;
    String hostname = null;

    if (cmd.hasOption(OPT_HELP)) {
        printHelp(true);
    }

    if (cmd.hasOption(OPT_USERNAME)) {
        username = cmd.getOptionValue(OPT_USERNAME);
    }

    if (cmd.hasOption(OPT_PASSWORD)) {
        password = cmd.getOptionValue(OPT_PASSWORD);
    }

    if (cmd.hasOption(OPT_IDENTITY)) {
        identity = new File(cmd.getOptionValue(OPT_IDENTITY));
        if (!identity.exists()) {
            System.err.println("[E] specified identity file," + identity + ", does not exist");
            System.exit(EXIT_ERROR);
        }
        if (!identity.isFile()) {
            System.err.println("[E] specified identity file" + identity + " is not a file");
            System.exit(EXIT_ERROR);
        }
        if (!identity.canRead()) {
            System.err.println("[E] specified identity file" + identity + " is not readable");
            System.exit(EXIT_ERROR);
        }
    }

    if (cmd.hasOption(OPT_IDENTITY_PASSWORD)) {
        identityPassword = cmd.getOptionValue(OPT_IDENTITY_PASSWORD);
    }

    if (cmd.hasOption(OPT_VERBOSE)) {
        verbose = true;
    }

    List<String> remArgs = cmd.getArgList();
    if (remArgs.size() == 0) {
        System.err.println("[E] You must specify an hostname");
        printHelp(true);
    }

    hostname = remArgs.remove(0);
    int exitCode = EXIT_ERROR;

    try {
        Connection conn = new Connection(hostname);
        conn.connect();

        boolean isAuthenticated = false;

        // 1. Password authentication requested
        if (password != null) {
            isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated) {
                info("Password authentication succeeded");
            } else {
                info("Password authentication failed");
            }
        } else {
            // 2. Pubkey authentication

            // 2.1 An identity file is specified use it 
            if (identity != null) {
                isAuthenticated = conn.authenticateWithPublicKey(username, identity, identityPassword);
                if (isAuthenticated) {
                    info("Pubkey authentication succeeded with " + identity);
                } else {
                    info("Pubkey authentication failed with " + identity);
                }
            } else {
                // 2.2 Try to find identity files automagically
                SshConfig config = new SshConfig();
                SSHKeys keys = new SSHKeys(config.getKeyDir());
                for (String id : keys.getKeys()) {
                    File f = new File(id);
                    if (!(f.exists() && f.isFile() && f.canRead())) {
                        continue;
                    }

                    isAuthenticated = conn.authenticateWithPublicKey(username, f, identityPassword);
                    info("Pubkey authentication succeeded with " + f);
                    if (isAuthenticated) {
                        break;
                    }
                }
            }
        }

        if (!isAuthenticated) {
            System.err.println("[E] Authentication failed");
            System.exit(2);
        }

        conn.setTCPNoDelay(true);
        Session sess = conn.openSession();

        sess.execCommand(buildCmdLine(remArgs));

        InputStream stdout = sess.getStdout();
        InputStream stderr = sess.getStderr();

        byte[] buffer = new byte[8192];

        while (true) {
            if ((stdout.available() == 0) && (stderr.available() == 0)) {

                /* Even though currently there is no data available, it may be that new data arrives
                 * and the session's underlying channel is closed before we call waitForCondition().
                 * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may
                 * be set together.
                 */
                int conditions = sess.waitForCondition(
                        ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 0);

                /* Wait no longer than 2 seconds (= 2000 milliseconds) */
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {

                    /* A timeout occured. */
                    throw new IOException("Timeout while waiting for data from peer.");
                }

                /* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
                if ((conditions & ChannelCondition.EOF) != 0) {

                    /* The remote side won't send us further data... */
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        // PROACTIVE-879: Ugly fix
                        // Calling Session.getExitStatus() can throw an NPE for an unknown reason
                        // After some investigation, I noticed that a subsequent call to this method could succeed
                        // So we try to call session.getExitStatus() until it does not throw an NPE or the timeout expires
                        TimeoutAccounter ta = TimeoutAccounter.getAccounter(1000);
                        while (!ta.isTimeoutElapsed()) {
                            try {
                                exitCode = sess.getExitStatus();
                                break;
                            } catch (NullPointerException e) {
                                Thread.yield();
                            }
                        }

                        break;
                    }
                }

                /* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */

                // You can be paranoid and check that the library is not going nuts:
                // if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)
                //   throw new IllegalStateException("Unexpected condition result (" + conditions + ")");
            }

            /* If you below replace "while" with "if", then the way the output appears on the local
             * stdout and stder streams is more "balanced". Addtionally reducing the buffer size
             * will also improve the interleaving, but performance will slightly suffer.
             * OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)
             */
            while (stdout.available() > 0) {
                int len = stdout.read(buffer);
                if (len > 0) { // this check is somewhat paranoid
                    System.out.write(buffer, 0, len);
                }
            }

            while (stderr.available() > 0) {
                int len = stderr.read(buffer);
                if (len > 0) { // this check is somewhat paranoid
                    System.err.write(buffer, 0, len);
                }
            }
        }

        sess.close();
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(EXIT_ERROR);
    }
    System.exit(exitCode);
}

From source file:Main.java

private static void sleep() {
    try {//from   w  w w.  jav  a 2 s  . c  om
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    Thread.yield();
}

From source file:Main.java

public static void yield() {
    Thread.yield();
}