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:org.gsoft.admin.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in//from   w ww.  j a  v a  2s.  c om
 * 
 * @param conn
 *            - the connection to use for the script
 * @param reader
 *            - the source of the script
 * @throws SQLException
 *             if any SQL errors occur
 * @throws IOException
 *             if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                println(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                println(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}

From source file:org.sakaiproject.search.indexer.impl.test.SequenceGeneratorDisabled.java

/**
 * Test method for/*from   w w w.  j  a  va 2 s .  c  o m*/
 * {@link org.sakaiproject.search.transaction.impl.TransactionSequenceImpl#getNextId()}.
 */
public final void testGetNextIdWrapped() {
    sequenceGenerator.setMinValue(10);
    sequenceGenerator.setMaxValue(200);
    log.info("================================== " + this.getClass().getName() + ".testGetNextId");
    nt = 0;
    fail = 0;
    last = 0;
    for (int i = 0; i < 20; i++) {
        Thread t = new Thread(new Runnable() {

            public void run() {
                try {
                    nt++;
                    long n = 0;
                    long locallast = 0;
                    Map<Long, Long> seq = new HashMap<Long, Long>();
                    for (int i = 0; i < 1000; i++) {
                        n = sequenceGenerator.getNextId();
                        if (n < last) {
                            log.debug("Wrapped " + last + ":" + n);
                            m = new ConcurrentHashMap<Long, Long>();
                        }
                        if (n < locallast) {
                            log.debug("Wrapped Local" + locallast + ":" + n);
                            seq = new HashMap<Long, Long>();
                        }
                        last = n;
                        locallast = n;
                        if (seq.get(n) != null) {
                            fail = n;
                            fail("Local clash on " + n);

                        }
                        seq.put(n, n);
                    }
                    log.debug("Last " + n);
                    for (long nx : seq.values()) {
                        if (m.get(nx) != null) {
                            fail = nx;
                            fail("Concurrent clash on " + nx);
                        }
                        m.put(nx, nx);
                    }
                } finally {
                    nt--;
                }

            }

        });
        t.start();
    }
    while (nt > 0) {
        if (fail != 0) {
            fail("Failed with clash on " + fail);
        }
        Thread.yield();
    }
    log.info("==PASSED========================== " + this.getClass().getName() + ".testGetNextId");

}

From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected RemoteTask wait(RemoteTask task, long now) throws Exception {
    if (task.getError() != null)
        throw task.getError();
    if (task.getResult() == null)
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
                String.format("%s returns empty contend instead of URI"));
    String result = task.getResult().toString();
    FibonacciSequence sequence = new FibonacciSequence();
    while (!task.poll()) {
        if (task.getError() != null)
            throw task.getError();
        Thread.sleep(sequence.sleepInterval(pollInterval, true, 1000 * 60 * 5));
        Thread.yield();
        if ((System.currentTimeMillis() - now) > pollTimeout)
            throw new ResourceException(Status.SERVER_ERROR_GATEWAY_TIMEOUT, String.format("%s %s ms > %s ms",
                    result == null ? task.getUrl() : result, System.currentTimeMillis() - now, pollTimeout));
    }/*from   w  w w  . j  a  v a2  s. c  o m*/

    if (task.getError() != null)
        if (task.getError() instanceof ResourceException)
            throw new ResourceException(Status.SERVER_ERROR_BAD_GATEWAY,
                    String.format("%s %d %s", result == null ? task.getUrl() : result,
                            ((ResourceException) task.getError()).getStatus().getCode(),
                            task.getError().getMessage()),
                    task.getError());
        else
            throw new ResourceException(
                    Status.SERVER_ERROR_BAD_GATEWAY, String.format("%s %s",
                            result == null ? task.getUrl() : result, task.getError().getMessage()),
                    task.getError());

    return task;
}

From source file:com.github.maven_nar.NarUtil.java

public static void deleteDirectory(final File dir) throws MojoExecutionException {
    int retries = OS.WINDOWS.equalsIgnoreCase(System.getProperty("os.name")) ? 3 : 1; // Windows file locking (such as due to virus scanners) and sometimes deleting slowly, or slow to report completion.
    while (retries > 0) {
        retries--;/*from ww w.  ja va  2  s. c  om*/
        try {
            FileUtils.deleteDirectory(dir);
            retries = 0;
        } catch (final IOException e) {
            if (retries > 0) {
                Thread.yield();
            } else {
                throw new MojoExecutionException("Could not delete directory: " + dir, e);
            }
        }
        if (retries > 0) {
            //      getLog().info("Could not delete directory: " + dir + " : Retrying");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
            }
            //TODO: if( windows and interactive ) prompt for retry?
            //@Component(role=org.codehaus.plexus.components.interactivity.Prompter.class, hint="archetype")
            //public class ArchetypePrompter
        }
    }
}

From source file:eu.openanalytics.rsb.EmailDepositITCase.java

private MimeMessage[] waitForRsbResponse() throws InterruptedException {
    MimeMessage[] receivedMessages = fetchMessagesFromUserMailBox();

    int attemptCount = 0;
    while ((receivedMessages.length == 0) && (attemptCount++ < 120)) {
        Thread.yield();
        Thread.sleep(250);/*from   ww  w  . j  av a  2  s  . c om*/
        receivedMessages = fetchMessagesFromUserMailBox();
    }
    return receivedMessages;
}

From source file:org.apache.streams.datasift.provider.DatasiftStreamProvider.java

@Override
//This is a hack.  It is only like this because of how perpetual streams work at the moment.  Read list server to debate/vote for new interfaces.
public StreamsResultSet readCurrent() {
    Queue<StreamsDatum> datums = Queues.newConcurrentLinkedQueue();
    StreamsDatum datum = null;//from w w w  . j  a  v  a2 s  .  c o m
    Interaction interaction;
    while (!this.interactions.isEmpty()) {
        interaction = this.interactions.poll();
        try {
            datum = new StreamsDatum(this.mapper.writeValueAsString(interaction.getData()),
                    interaction.getData().get("interaction").get("id").textValue());
        } catch (JsonProcessingException jpe) {
            LOGGER.error("Exception while converting Interaction to String : {}", jpe);
        }
        if (datum != null) {
            while (!datums.offer(datum)) {
                Thread.yield();
            }
        }

    }
    return new StreamsResultSet(datums);
}

From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java

private void waitFor(final InputStream input, final String expectedLine) throws Exception {
    final long startMillis = System.currentTimeMillis();
    final StringBuilder content = new StringBuilder();
    do {//  w w w.  j a  va2 s . co  m
        final int available = input.available();
        if (available > 0) {
            final byte[] bytes = new byte[available];
            input.read(bytes);
            final String current = new String(bytes);
            System.out.print(current);
            content.append(current);
            Thread.yield();
        } else if (System.currentTimeMillis() - startMillis > 5 * 60 * 1000) {
            throw new InterruptedException(); // waited for more than 5 minutes
        } else {
            try {
                Thread.sleep(100);
            } catch (final InterruptedException e) {
                // continue...
            }
        }
    } while (content.indexOf(expectedLine) == -1);
    System.out.println();
}

From source file:com.indeed.lsmtree.core.TestImmutableBTreeIndex.java

public void testRandom() throws Exception {
    final int[] ints = createTree();
    final ImmutableBTreeIndex.Reader<Integer, Long> reader = new ImmutableBTreeIndex.Reader(tmpDir,
            new IntSerializer(), new LongSerializer(), false);
    final int max = ints[ints.length - 1];
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < 8; i++) {
        final int index = i;
        new Thread(new Runnable() {
            @Override//from  w  w  w.j  ava 2s. c om
            public void run() {
                try {
                    final Random r = new Random(index);
                    for (int i = 0; i < treeSize; i++) {
                        int rand = r.nextInt(max + 1);
                        int insertionindex = Arrays.binarySearch(ints, rand);
                        final Iterator<Generation.Entry<Integer, Long>> iterator = reader.iterator(rand, true);
                        try {
                            assertTrue(iterator.hasNext());
                        } catch (Throwable t) {
                            System.err.println("rand: " + rand);
                            throw Throwables.propagate(t);
                        }
                        Generation.Entry<Integer, Long> entry = iterator.next();
                        assertTrue("entry: " + entry + " rand: " + rand, entry.getKey() >= rand);
                        assertTrue(entry.getKey().longValue() == entry.getValue());
                        if (insertionindex >= 0) {
                            assertTrue(rand == ints[insertionindex]);
                            assertTrue(entry.getKey() == rand);
                            Generation.Entry<Integer, Long> result = reader.get(rand);
                            assertTrue(result.getValue() == rand);
                        } else {
                            if (insertionindex != -1)
                                assertTrue(ints[(~insertionindex) - 1] < rand);
                            assertTrue(
                                    "insertionindex: " + insertionindex + " entry: " + entry
                                            + " ints[!insertionindex]" + ints[~insertionindex],
                                    ints[~insertionindex] == entry.getKey());
                            Generation.Entry<Integer, Long> result = reader.get(rand);
                            assertTrue(result == null);
                        }
                    }
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    reader.close();
}

From source file:org.apache.hadoop.hbase.stargate.TestRowResource.java

Response putValuePB(String table, String row, String column, String value) throws IOException {
    StringBuilder path = new StringBuilder();
    path.append('/');
    path.append(table);/*from  ww w. j a va  2s.  c  om*/
    path.append('/');
    path.append(row);
    path.append('/');
    path.append(column);
    RowModel rowModel = new RowModel(row);
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value)));
    CellSetModel cellSetModel = new CellSetModel();
    cellSetModel.addRow(rowModel);
    Response response = client.put(path.toString(), MIMETYPE_PROTOBUF, cellSetModel.createProtobufOutput());
    Thread.yield();
    return response;
}

From source file:BenchmarkApplet.java

public synchronized void println(String s) {
      if (console.getState())
          System.out.println(s);/* ww  w  .j  a v a  2s  . co  m*/
      out.appendText(s + newline);
      clear.enable();
      Thread.yield(); // give interface a chance to process events
  }