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.amazonaws.metrics.internal.cloudwatch.MetricUploaderThread.java

@Override
public void run() {
    while (!cancelled) {
        try {//w w w.j  av a 2 s. c om
            Iterable<PutMetricDataRequest> requests = qIterator.nextUploadUnits();
            for (PutMetricDataRequest req : requests) {
                log.debug(req);
                cloudwatchClient.putMetricData(req);
                Thread.yield();
            }
        } catch (InterruptedException e) {
            if (!cancelled) {
                log.debug("Unexpected interruption ignored");
            }
        } catch (Throwable t) {
            log.warn("Unexpected condition; soldier on", t);
            Thread.yield();
        }
    }
}

From source file:org.apache.streams.rss.provider.RssLinkProvider.java

@Override
public StreamsResultSet readCurrent() {
    Queue<StreamsDatum> result = Queues.newConcurrentLinkedQueue();
    synchronized (this.entries) {
        if (this.entries.isEmpty() && this.doneProviding.get()) {
            this.keepRunning.set(false);
        }//from   www.ja v a  2  s.  co  m

        while (!this.entries.isEmpty()) {
            ObjectNode node = this.entries.poll();

            try {
                while (!result.offer(new StreamsDatum(node.get("uri").asText()))) {
                    Thread.yield();
                }
            } catch (Exception e) {
                LOGGER.error("Problem offering up new StreamsDatum: {}", node.asText());
            }
        }
    }
    LOGGER.debug("** ReadCurrent return {} streams datums", result.size());

    return new StreamsResultSet(result);
}

From source file:org.apache.jackrabbit.oak.plugins.document.persistentCache.CacheTest.java

@Test
public void recoverIfCorrupt() throws Exception {
    FileUtils.deleteDirectory(new File("target/cacheTest"));
    new File("target/cacheTest").mkdirs();
    FileOutputStream out = new FileOutputStream("target/cacheTest/cache-0.data");
    out.write("corrupt".getBytes());
    out.close();//from  w  w w. ja  v  a  2 s  .  co m
    PersistentCache pCache = new PersistentCache("target/cacheTest");
    CacheLIRS<PathRev, StringValue> cache = new CacheLIRS.Builder<PathRev, StringValue>().maximumSize(1)
            .build();
    Cache<PathRev, StringValue> map = pCache.wrap(null, null, cache, CacheType.DIFF);
    String largeString = new String(new char[1024 * 1024]);
    for (int counter = 0; counter < 10; counter++) {
        long end = System.currentTimeMillis() + 100;
        while (System.currentTimeMillis() < end) {
            Thread.yield();
        }
        for (int i = 0; i < 100; i++) {
            PathRev k = new PathRev("/" + counter, new RevisionVector(new Revision(0, 0, i)));
            map.getIfPresent(k);
            map.put(k, new StringValue(largeString));
        }
    }
    assertTrue("Exceptions: " + pCache.getExceptionCount(), pCache.getExceptionCount() < 100);
}

From source file:Main.java

/**
 * Compute e^x to a given scale by the Taylor series.
 * @param x the value of x/*  w  w  w.  j ava  2 s.  c om*/
 * @param scale the desired scale of the result
 * @return the result value
 */
private static BigDecimal expTaylor(BigDecimal x, int scale) {
    BigDecimal factorial = BigDecimal.valueOf(1);
    BigDecimal xPower = x;
    BigDecimal sumPrev;

    // 1 + x
    BigDecimal sum = x.add(BigDecimal.valueOf(1));

    // Loop until the sums converge
    // (two successive sums are equal after rounding).
    int i = 2;
    do {
        // x^i
        xPower = xPower.multiply(x).setScale(scale, BigDecimal.ROUND_HALF_EVEN);

        // i!
        factorial = factorial.multiply(BigDecimal.valueOf(i));

        // x^i/i!
        BigDecimal term = xPower.divide(factorial, scale, BigDecimal.ROUND_HALF_EVEN);

        // sum = sum + x^i/i!
        sumPrev = sum;
        sum = sum.add(term);

        ++i;
        Thread.yield();
    } while (sum.compareTo(sumPrev) != 0);

    return sum;
}

From source file:net.jradius.server.Processor.java

public void run() {
    while (getActive()) {
        try {// w ww.j a  va2  s  .  c  om
            Thread.yield();
            process();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Throwable e) {
            e.printStackTrace();
            log.error("Error in radius task Processor", e);
        }
    }
}

From source file:com.espertech.esper.core.service.InsertIntoLatchSpin.java

/**
 * Blocking call that returns only when the earlier latch completed.
 * @return payload of the latch/*from www  . jav  a 2 s .co m*/
 */
public EventBean await() {
    if (!earlier.isCompleted) {
        long spinStartTime = factory.getTimeSourceService().getTimeMillis();

        while (!earlier.isCompleted) {
            Thread.yield();

            long spinDelta = factory.getTimeSourceService().getTimeMillis() - spinStartTime;
            if (spinDelta > msecTimeout) {
                log.info("Spin wait timeout exceeded in insert-into dispatch at " + msecTimeout + "ms for "
                        + factory.getName()
                        + ", consider disabling insert-into between-statement latching for better performance");
                break;
            }
        }
    }

    return payload;
}

From source file:elsu.support.XMLViewer.java

/**
 * showConfigNodes(...) method is used to recursively scan the XML config
 * file and display the nodes in tree format.
 *
 * @param parent/*w w  w. j a va 2s  .c  om*/
 * @param level level of the node, increased for each child-node to allow
 * tabbed tree display output
 *
 */
protected void showConfig(org.w3c.dom.Node parent, int level) {
    // create a local class to display node value/text and associated
    // node attributes
    class SubShowNode {

        // loop through the node attributes for the node passed
        String displayNodeAttributes(org.w3c.dom.Node node) {
            // if node is null, return empty string
            if (node == null) {
                return "";
            }

            // create string build object to support string concatanation
            StringBuilder sb = new StringBuilder();

            // retrieve node attributes (if any)
            ArrayList<Node> nAttributes = _xmlr.getNodeAttributes(node);

            // loop through the attributes array and append them to the
            // string builder object
            if (nAttributes != null) {
                for (Object na : nAttributes) {
                    // append the attribute details (key/text) to the string
                    // builder object
                    if (na != null) {
                        sb.append(" [ATTR=").append(((org.w3c.dom.Node) na).getNodeName()).append("//")
                                .append(((org.w3c.dom.Node) na).getNodeValue()).append("]");
                    }

                    // yield processing to other threads
                    Thread.yield();
                }
            }

            // return the string builder representation as a string
            return sb.toString();
        }
    }

    // declare the showNode class to allow methods to reference the display
    // method to prevent duplicaion in code
    SubShowNode showNode = new SubShowNode();

    // retrieve the child nodes for processing
    ArrayList<Node> nodes = _xmlr.getNodeChildren(parent);

    // if node level is 1, then this is root node, display it with no
    // indentation
    if (level == 1) {
        // display the parent node name
        String data = org.apache.commons.lang3.StringUtils.repeat('~', level) + parent.getNodeName();

        // use the sub function to extract node attributes
        data += showNode.displayNodeAttributes(parent);

        // display all collected data to the user output
        System.out.println(data);
    }

    // parse the list of child nodes for the node being processed
    if (nodes != null) {
        for (Object node : nodes) {
            // display the parent node name
            String data = org.apache.commons.lang3.StringUtils.repeat('\t', level)
                    + ((org.w3c.dom.Node) node).getNodeName();

            // use the sub function to extract node attributes
            data += showNode.displayNodeAttributes((org.w3c.dom.Node) node);

            // if node has a text value, display the text
            if (_xmlr.getNodeText((org.w3c.dom.Node) node) != null) {
                data += " (TEXT=" + _xmlr.getNodeText((org.w3c.dom.Node) node) + ")";
            }

            // display all collected data to the user output
            System.out.println(data);

            // recall the function (recursion) to see if the node has child 
            // nodes and preocess them in hierarchial level
            showConfig((org.w3c.dom.Node) node, (level + 1));

            // yield processing to other threads
            Thread.yield();
        }
    }
}

From source file:com.dataartisans.queryablestatedemo.BumpEventGeneratorSource.java

@Override
public void run(SourceContext<BumpEvent> sourceContext) throws Exception {
    final Random rand = new Random();
    final AtomicLong count = new AtomicLong();

    Thread throughputLogger = null;
    if (printThroughput) {
        throughputLogger = new Thread(new ThroughputLogger(count), "ThroughputLogger");
        throughputLogger.start();/*from w  ww.  j a v  a 2  s .  co  m*/
    }

    try {
        while (running) {
            // Generate random events
            final int userId = rand.nextInt(Integer.MAX_VALUE);

            final String itemCase = RandomStringUtils.randomAlphanumeric(ITEM_ID_NUM_CHARS).toLowerCase();

            synchronized (sourceContext.getCheckpointLock()) {
                sourceContext.collect(new BumpEvent(userId, itemCase));
            }

            // Increment count for throughput logger
            count.incrementAndGet();

            Thread.yield();
        }
    } finally {
        if (throughputLogger != null) {
            throughputLogger.interrupt();
            throughputLogger.join();
        }
    }
}

From source file:org.mwc.cmap.media.views.images.ImageLoader.java

public void load(ImagePanel panel) {
    synchronized (loaderMutex) {
        boolean load = false;
        if (panel.shouldLoadCurrentImage()) {
            load = true;// ww w  .  j  ava  2s .c om
            labelsToLoad.add(new ImagePanelLoader(panel.getCurrentImageFile(), panel));
            panel.currentImagePassedToLoad();
        }
        if (panel.shouldLoadNextImage()) {
            load = true;
            labelsToLoad.add(new ImagePanelLoader(panel.getNextImageFile(), panel));
            panel.nextImagePassedToLoad();
        }
        if (load) {
            loaderMutex.notify();
            Thread.yield();
        }
    }
}

From source file:com.espertech.esper.core.InsertIntoLatchSpin.java

/**
 * Blocking call that returns only when the earlier latch completed.
 * @return payload of the latch/*from  w w w.  jav  a  2s.  c  om*/
 */
public EventBean await() {
    if (!earlier.isCompleted) {
        long spinStartTime = timeSourceService.getTimeMillis();

        while (!earlier.isCompleted) {
            Thread.yield();

            long spinDelta = timeSourceService.getTimeMillis() - spinStartTime;
            if (spinDelta > msecTimeout) {
                log.info("Spin wait timeout exceeded in insert-into dispatch at " + msecTimeout
                        + "ms, consider disabling insert-into between-statement latching for better performance");
                break;
            }
        }
    }

    return payload;
}