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:Main.java

/**
 * Compute e^x to a given scale. Break x into its whole and fraction parts
 * and compute (e^(1 + fraction/whole))^whole using Taylor's formula.
 * // w  w  w. j  a va  2  s .  c o m
 * @param x
 *            the value of x
 * @param scale
 *            the desired scale of the result
 * @return the result value
 */
public static BigDecimal exp(BigDecimal x, int scale) {
    // e^0 = 1
    if (x.signum() == 0) {
        return BigDecimal.valueOf(1);
    }

    // If x is negative, return 1/(e^-x).
    else if (x.signum() == -1) {
        return BigDecimal.valueOf(1).divide(exp(x.negate(), scale), scale, BigDecimal.ROUND_HALF_EVEN);
    }

    // Compute the whole part of x.
    BigDecimal xWhole = x.setScale(0, BigDecimal.ROUND_DOWN);

    // If there isn't a whole part, compute and return e^x.
    if (xWhole.signum() == 0) {
        return expTaylor(x, scale);
    }

    // Compute the fraction part of x.
    BigDecimal xFraction = x.subtract(xWhole);

    // z = 1 + fraction/whole
    BigDecimal z = BigDecimal.valueOf(1).add(xFraction.divide(xWhole, scale, BigDecimal.ROUND_HALF_EVEN));

    // t = e^z
    BigDecimal t = expTaylor(z, scale);

    BigDecimal maxLong = BigDecimal.valueOf(Long.MAX_VALUE);
    BigDecimal result = BigDecimal.valueOf(1);

    // Compute and return t^whole using intPower().
    // If whole > Long.MAX_VALUE, then first compute products
    // of e^Long.MAX_VALUE.
    while (xWhole.compareTo(maxLong) >= 0) {
        result = result.multiply(intPower(t, Long.MAX_VALUE, scale)).setScale(scale,
                BigDecimal.ROUND_HALF_EVEN);
        xWhole = xWhole.subtract(maxLong);

        Thread.yield();
    }
    return result.multiply(intPower(t, xWhole.longValue(), scale)).setScale(scale, BigDecimal.ROUND_HALF_EVEN);
}

From source file:fi.jumi.core.stdout.SynchronizedPrintStreamTest.java

/**
 * For example {@link Throwable#printStackTrace} does this, we must be careful to always acquire a lock on the
 * monitor of the PrintStream first, before all other locks.
 *//*from ww  w  .  j ava2 s.co m*/
@Test
public void does_not_deadlock_if_somebody_locks_in_the_PrintStream_externally() throws Exception {
    final int ITERATIONS = 10;
    PrintStream printStream = SynchronizedPrintStream.create(new NullOutputStream(), Charset.defaultCharset(),
            lock);

    // will fail with a test timeout if a deadlock happens
    runConcurrently(() -> {
        // what Thread.printStackTrace() would do
        synchronized (printStream) {
            for (int i = 0; i < ITERATIONS; i++) {
                Thread.yield();
                printStream.print("X");
            }
        }
    }, () -> {
        // what a normal printer would do
        for (int i = 0; i < ITERATIONS; i++) {
            Thread.yield();
            printStream.print("X");
        }
    });
}

From source file:com.thoughtworks.go.helpers.FileSystemUtils.java

public static File createFile(String filename, File directory) throws IOException {
    final File file = new File(directory, filename);

    // attempt workaround for intermitent w2k error:
    // java.io.IOException: Access is denied
    // at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    // at java.io.File.createNewFile(File.java:883)
    // at net.sourceforge.cruisecontrol.dashboard.testhelpers.FilesystemUtils.createFile(FilesystemUtils.java:94)
    // ...//  w  w w. j  av  a  2s  .c o m
    // see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6198547
    // see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6325169
    int count = 0;
    IOException lastIOException = null;
    do {
        try {
            file.createNewFile();
        } catch (IOException e) {
            lastIOException = e;
            Thread.yield();
        }
        count++;
    } while (!file.exists() && count < 3);

    // another attempt to workaround the above bugs, using approach similar to that of Ant MkDirs taskdef
    // see Util.doMkDirs()
    if (!file.exists()) {
        try {
            Thread.sleep(10);
            try {
                file.createNewFile();
            } catch (IOException e) {
                lastIOException = e;
            }
        } catch (InterruptedException ex) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                lastIOException = e;
            }
        }
    }

    if (!file.exists()) {
        if (lastIOException != null) {
            throw new RuntimeException("Error creating file: " + file.getAbsolutePath(), lastIOException);
        } else {
            throw new RuntimeException("Error creating file: " + file.getAbsolutePath());
        }
    }

    file.deleteOnExit();
    return file;
}

From source file:org.apache.synapse.transport.vfs.VFSEchoRawXMLTest.java

public void testXMLFileInDirectory() throws Exception {

    Options options = new Options();
    options.setTo(new EndpointReference(
            "vfs:file:" + new File(".").getAbsolutePath() + File.separator + "target/vfs1/req/request.xml"));
    options.setAction(Constants.AXIS2_NAMESPACE_URI + "/echoOMElementNoResponse");

    ServiceClient sender = new ServiceClient(getClientCfgCtx(), null);
    sender.setOptions(options);/*w w w. j ava 2s .  co  m*/
    sender.fireAndForget(createPayload());

    Thread.yield();
    Thread.sleep(1000 * 5);

    File req = new File("./target/vfs1/req/request.xml");
    if (req.exists()) {
        fail("Request file still exists. Not processed by service? : " + req.getPath());
    }

    File res = new File("target/vfs1/res/response.xml");
    if (!res.exists()) {
        fail("Response file not created : " + res.getPath());
    }
}

From source file:de.mklinger.commons.exec.PipeRunnable.java

public void waitForStart(final long timeoutMillis) throws CommandLineException {
    final long start = System.currentTimeMillis();
    while (!started.get()) {
        if (start + timeoutMillis < System.currentTimeMillis()) {
            throw new CommandLineException("Timout waiting for pipe to start after " + timeoutMillis + " ms");
        }//from  w w w.  j  a  v  a 2  s . c o m
        Thread.yield();
    }
}

From source file:de.hybris.platform.impex.jalo.PLA_12772_Test.java

private void doTest() throws ImpExException {
    final ThreadPool pool = createWorkerThreadPool(); // use pool of our own to avoid race conditions with cronjob and others
    try {//from  w  w  w . ja  v  a  2  s. com
        final int max = pool.getMaxActive();

        // start first job using almost all workers ( max - 2 ( reader + result proc ) - 3 ( rest for next run ) )
        final MultiThreadedImporter importer1 = createImporter(max - 5, createTestCSV(1000, 0), pool);
        Item last1;
        last1 = importer1.importNext(); // this starts importing

        Thread.yield();
        assertTrue(pool.getNumActive() > 0);

        // start next job trying to get more workers than possible
        final MultiThreadedImporter importer2 = createImporter(10, createTestCSV(1000, 1000), pool);
        Item last2;
        last2 = importer2.importNext(); // this starts importing as well

        // now try to consume both 

        do {
            if (last1 != null) {
                last1 = importer1.importNext();
            }
            if (last2 != null) {
                last2 = importer2.importNext();
            }
        } while (last1 != null || last2 != null);

        assertEquals("still got used workers", 0, waitForWorkerToReturnToPoolAndGetUsedNow(pool, 30));
    } finally {
        pool.close();
    }
}

From source file:com.quinsoft.zeidon.utils.TimedLruCache.java

public TimedLruCache(long timeToLiveInSeconds, final long timerIntervalInSeconds, int maxItems) {
    this.timeToLiveInMillis = timeToLiveInSeconds * 1000;

    cacheMap = new LRUMap(maxItems);

    if (timeToLiveInMillis > 0 && timerIntervalInSeconds > 0) {

        Thread t = new Thread(new Runnable() {
            @Override//  ww  w.j  a v a2  s  . c o  m
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(timerIntervalInSeconds * 1000);
                    } catch (InterruptedException ex) {
                    }

                    cleanup();
                    Thread.yield();
                }
            }
        });

        t.setDaemon(true);
        t.start();
    }
}

From source file:test.com.azaptree.services.spring.application.SpringApplicationServiceTest.java

@Test
public void testSpringApplicationService() throws Exception {
    final String[] args = { "classpath:spring-application-service.xml" };

    try {//from   w w w. j a  v a  2  s. co m
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    SpringApplicationService.main(args);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.yield();

        ApplicationContext ctx = SpringApplicationService.getApplicationContext();
        while (ctx == null) {
            log.info("Waiting for ApplicationContext to initialize ...");
            Thread.sleep(100l);
            ctx = SpringApplicationService.getApplicationContext();
        }
        Assert.assertNotNull(ctx);
        final Properties props = ctx.getBean("systemProps", Properties.class);
        Assert.assertNotNull(props);
        Assert.assertFalse(CollectionUtils.isEmpty(props));

        Assert.assertEquals(props.getProperty("app.env"), "DEV");

        final Map<String, String> env = ctx.getBean("env", Map.class);
        Assert.assertNotNull(env);
        Assert.assertFalse(CollectionUtils.isEmpty(env));

        final Map<String, String> environment = ctx.getBean("environment", Map.class);
        Assert.assertNotNull(environment);
        Assert.assertFalse(CollectionUtils.isEmpty(environment));

        log.info("bean count: {}", ctx.getBeanDefinitionCount());
        for (String beanName : ctx.getBeanDefinitionNames()) {
            log.info("beanName: {}", beanName);
        }
    } finally {
        SpringApplicationService.shutdown();
    }
}

From source file:org.ros.android.acm_serial.PollingInputStream.java

/**
 * @param inputStream/*from ww  w  .j  a v a 2s.  c  o  m*/
 *          the {@link InputStream} to read from
 * @param executorService
 *          used to execute the read loop
 */
public PollingInputStream(final InputStream inputStream, ExecutorService executorService) {
    readBuffer = new byte[BUFFER_CAPACITY];
    readPosition = 0;
    writePosition = 0;
    executorService.execute(new CancellableLoop() {
        @Override
        protected void loop() throws InterruptedException {
            try {
                while (remaining() < READ_SIZE) {
                    if (readPosition < remaining()) {
                        // There isn't enough room to compact the buffer yet. We will most
                        // likely start dropping messages.
                        log.error("Not enough room to compact buffer.");
                        Thread.yield();
                        continue;
                    }
                    synchronized (readBuffer) {
                        int remaining = remaining();
                        System.arraycopy(readBuffer, writePosition, readBuffer, 0, remaining);
                        writePosition = remaining;
                        readPosition = 0;
                        if (DEBUG) {
                            log.info(String.format("Buffer compacted. %d bytes remaining.", remaining()));
                        }
                    }
                }
                int bytesRead = inputStream.read(readBuffer, writePosition, READ_SIZE);
                if (bytesRead < 0) {
                    throw new IOException("Stream closed.");
                }
                writePosition += bytesRead;
            } catch (IOException e) {
                throw new RosRuntimeException(e);
            }
        }
    });
}

From source file:MainClass.java

public void run() {
    byte[] buffer = new byte[65507];
    while (true) {
        if (stopped)
            return;
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
        try {/*from  ww  w  .j a  v  a 2s .  co  m*/
            socket.receive(dp);
            String s = new String(dp.getData(), 0, dp.getLength());
            System.out.println(s);
            Thread.yield();
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}