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:axiom.util.Logging.java

/**
 * Shut down logging, stopping the logger thread and closing all logs.
 *///from   w  w  w . j  a  va 2 s. c  om
public synchronized static void shutdown() {
    if (runner != null && runner.isAlive()) {
        runner.interrupt();
    }
    runner = null;
    Thread.yield();
    closeAll();
}

From source file:com.espertech.esper.epl.named.NamedWindowConsumerLatchSpin.java

/**
 * Blocking call that returns only when the earlier latch completed.
 * @return unit of the latch//  ww w  .  j a  v  a  2s.  c om
 */
public void await() {
    if (earlier.isCompleted) {
        currentThread = Thread.currentThread();
        return;
    }

    if (earlier.getCurrentThread() == Thread.currentThread()) {
        currentThread = Thread.currentThread();
        return;
    }

    long spinStartTime = factory.getTimeSourceService().getTimeMillis();
    while (!earlier.isCompleted) {
        Thread.yield();
        long spinDelta = factory.getTimeSourceService().getTimeMillis() - spinStartTime;
        if (spinDelta > factory.getMsecWait()) {
            log.info("Spin wait timeout exceeded in named window '" + factory.getName()
                    + "' consumer dispatch at " + factory.getMsecWait() + "ms for " + factory.getName()
                    + ", consider disabling named window consumer dispatch latching for better performance");
            break;
        }
    }
}

From source file:org.stanwood.podcaster.util.StreamGobbler.java

/**
 * Used to mark the stream has done and block till it's not running
 *///from  w w w . ja  v  a 2  s  .c o m
@Override
public void done() {
    done = true;
    // Block until it finishes
    while (running) {
        Thread.yield();
    }
}

From source file:org.apache.hadoop.metrics2.impl.TestSinkQueue.java

/**
 * Test blocking when queue is empty/*from www.ja v  a 2 s.c  o m*/
 * @throws Exception
 */
@Test
public void testEmptyBlocking() throws Exception {
    final SinkQueue<Integer> q = new SinkQueue<Integer>(2);
    final Runnable trigger = mock(Runnable.class);
    // try consuming emtpy equeue and blocking
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                assertEquals("element", 1, (int) q.dequeue());
                q.consume(new Consumer<Integer>() {
                    public void consume(Integer e) {
                        assertEquals("element", 2, (int) e);
                        trigger.run();
                    }
                });
            } catch (InterruptedException e) {
                LOG.warn("Interrupted", e);
            }
        }
    };
    t.start();
    Thread.yield(); // Let the other block
    q.enqueue(1);
    q.enqueue(2);
    t.join();
    verify(trigger).run();
}

From source file:org.archive.util.CachedBdbMapTest.java

@SuppressWarnings("unchecked")
public void xestReadConsistencyUnderLoad() throws Exception {
    final CachedBdbMap<String, AtomicInteger> cbdbmap = new CachedBdbMap(this.envDir, this.getClass().getName(),
            Integer.class, AtomicInteger.class);
    try {//from  w  ww. j a va 2s.  co m
        final AtomicInteger level = new AtomicInteger(0);
        final int keyCount = 128 * 1024; // 128K  keys
        final int maxLevel = 64;
        // initial fill
        for (int i = 0; i < keyCount; i++) {
            AtomicInteger prevVal = cbdbmap.putIfAbsent("" + i, new AtomicInteger(level.get()));
            assertNull("unexpected prior value", prevVal);
        }
        // backward checking that all values always at level or higher
        new Thread() {
            public void run() {
                untilmax: while (true) {
                    for (int j = keyCount - 1; j >= 0; j--) {
                        int targetValue = level.get();
                        if (targetValue >= maxLevel) {
                            break untilmax;
                        }
                        assertTrue("stale value revseq key " + j, cbdbmap.get(j).get() >= targetValue);
                        Thread.yield();
                    }
                }
            }
        }.start();
        // random checking that all values always at level or higher
        new Thread() {
            public void run() {
                untilmax: while (true) {
                    int j = RandomUtils.nextInt(keyCount);
                    int targetValue = level.get();
                    if (targetValue >= maxLevel) {
                        break untilmax;
                    }
                    assertTrue("stale value random key " + j, cbdbmap.get("" + j).get() >= targetValue);
                    Thread.yield();
                }
            }
        }.start();
        // increment all keys
        for (; level.get() < maxLevel; level.incrementAndGet()) {
            for (int k = 0; k < keyCount; k++) {
                int foundValue = cbdbmap.get("" + k).getAndIncrement();
                assertEquals("stale value preinc key " + k, level.get(), foundValue);
            }
            if (level.get() % 10 == 0) {
                System.out.println("level to " + level.get());
            }
            Thread.yield();
        }
    } finally {
        cbdbmap.close();
    }
    // SUCCESS
}

From source file:org.openhab.binding.fibaro.internal.InMemoryCache.java

@SuppressWarnings("unchecked")
public void cleanup() {

    long now = System.currentTimeMillis();
    ArrayList<K> deleteKey = null;

    synchronized (crunchifyCacheMap) {
        MapIterator itr = crunchifyCacheMap.mapIterator();

        deleteKey = new ArrayList<K>((crunchifyCacheMap.size() / 2) + 1);
        K key;//from  ww w .j ava  2 s  .c  om
        CacheObject c;

        while (itr.hasNext()) {
            key = (K) itr.next();
            c = (CacheObject) itr.getValue();

            if (c != null && (now > (timeToLive + c.lastAccessed))) {
                deleteKey.add(key);
            }
        }
    }

    for (K key : deleteKey) {
        synchronized (crunchifyCacheMap) {
            crunchifyCacheMap.remove(key);
        }

        Thread.yield();
    }
}

From source file:com.ottogroup.bi.asap.server.emitter.kafka.KafkaTopicPartitionConsumer.java

/**
 * @see java.lang.Runnable#run()/*from ww w .  java2 s .  co m*/
 */
public void run() {

    ConsumerIterator<byte[], byte[]> topicPartitionStreamIterator = this.kafkaTopicPartitionStream.iterator();

    this.running = true;
    // ensure that the partition iterator still has some elements left and the receiving
    // web socket producer still wants more
    while (running) {
        if (topicPartitionStreamIterator.hasNext()) {
            // next message must neither be null nor empty
            MessageAndMetadata<byte[], byte[]> message = topicPartitionStreamIterator.next();
            if (message != null && message.message() != null && message.message().length > 0) {
                // try to convert the content into a UTF-8 encoded string
                String messageContent = new String(message.message(), CharsetUtil.UTF_8);

                // return only if the message is not empty or blank
                // as we do not transport sender references it is forwarded with a reference to a dead letter box
                if (StringUtils.isNotBlank(messageContent)) {
                    messages.add(new StreamingDataMessage(origin, messageContent, System.currentTimeMillis()));
                }
            }
        } else {
            Thread.yield();
            // TODO wait strategy
        }
    }
}

From source file:com.auditbucket.registration.service.TagService.java

public Collection<TagInputBean> processTags(final Company company, final List<TagInputBean> tagInputs) {
    //schemaDao.ensureUniqueIndexes(company, tagInputs);
    Future<Collection<TagInputBean>> future = makeTags(company, tagInputs);
    while (!future.isDone())
        Thread.yield();
    try {/*w w  w  . j  a v a2  s. c o  m*/
        return future.get();
    } catch (InterruptedException | ExecutionException e) {
        logger.error("Processing tags", e);
    }
    return null;
}

From source file:ThreadDemo.java

/** This is the dummy method our threads all call */
static synchronized void compute() {
    // Figure out how many times we've been called by the current thread
    Integer n = (Integer) numcalls.get();
    if (n == null)
        n = new Integer(1);
    else/*from w ww  .j  a  v a2  s.  co m*/
        n = new Integer(n.intValue() + 1);
    numcalls.set(n);

    // Display the name of the thread, and the number of times called
    System.out.println(Thread.currentThread().getName() + ": " + n);

    // Do a long computation, simulating a "compute-bound" thread
    for (int i = 0, j = 0; i < 1000000; i++)
        j += i;

    // Alternatively, we can simulate a thread subject to network or I/O
    // delays by causing it to sleep for a random amount of time:
    try {
        // Stop running for a random number of milliseconds
        Thread.sleep((int) (Math.random() * 100 + 1));
    } catch (InterruptedException e) {
    }

    // Each thread politely offers the other threads a chance to run.
    // This is important so that a compute-bound thread does not "starve"
    // other threads of equal priority.
    Thread.yield();
}

From source file:org.sonatype.nexus.testsuite.p2.nxcm1995.NXCM1995MetadataCacheIT.java

@Test
@Ignore//from www  . ja va 2  s.  c  om
public void test() throws Exception {
    // check original content
    final File f1 = downloadFile(new URL(getNexusTestRepoUrl() + "/content.xml"),
            "target/downloads/nxcm1995/1/content.xml");
    assertThat(f1, exists());
    assertThat(f1, contains("com.adobe.flexbuilder.utils.osnative.win"));
    assertThat(f1, not(contains("com.sonatype.nexus.p2.its.feature2.feature.jar")));

    // check original artifact
    final File a1 = downloadFile(new URL(getNexusTestRepoUrl() + "/artifacts.xml"),
            "target/downloads/nxcm1995/1/artifacts.xml");
    assertThat(a1, exists());
    assertThat(a1, contains("com.adobe.flexbuilder.multisdk"));
    assertThat(a1, not(contains("com.sonatype.nexus.p2.its.feature2")));

    final File reponxcm1995 = new File(localStorageDir, "nxcm1995");

    // check new content
    final File newContentXml = new File(localStorageDir, "p2repo2/content.xml");
    assertThat(newContentXml, exists());
    assertThat(newContentXml, not(contains("com.adobe.flexbuilder.utils.osnative.win")));
    assertThat(newContentXml, contains("com.sonatype.nexus.p2.its.feature2.feature.jar"));
    FileUtils.copyFileToDirectory(newContentXml, new File(reponxcm1995, "memberrepo1"), false);
    FileUtils.copyFileToDirectory(newContentXml, new File(reponxcm1995, "memberrepo2"), false);

    final File newArtifactsXml = new File(localStorageDir, "p2repo2/artifacts.xml");
    assertThat(newArtifactsXml, exists());
    FileUtils.copyFileToDirectory(newArtifactsXml, new File(reponxcm1995, "memberrepo1"), false);
    FileUtils.copyFileToDirectory(newArtifactsXml, new File(reponxcm1995, "memberrepo2"), false);

    // metadata cache expires in ONE minute, so let's give it some time to expire
    Thread.yield();
    Thread.sleep(1 * 60 * 1000);
    Thread.yield();
    Thread.sleep(1 * 60 * 1000);
    Thread.yield();

    // ScheduledServicePropertyResource prop = new ScheduledServicePropertyResource();
    // prop.setId( "repositoryId" );
    // prop.setValue( REPO );
    // TaskScheduleUtil.runTask( ExpireCacheTaskDescriptor.ID, prop );
    // TaskScheduleUtil.waitForAllTasksToStop();

    // make sure nexus has the right content after metadata cache expires
    final File f2 = downloadFile(new URL(getNexusTestRepoUrl() + "/content.xml"),
            "target/downloads/nxcm1995/2/content.xml");
    assertThat(f2, exists());
    assertThat(f2, not(contains("com.adobe.flexbuilder.utils.osnative.win")));
    assertThat(f2, contains("com.sonatype.nexus.p2.its.feature2.feature.jar"));

    assertThat(FileTestingUtils.compareFileSHA1s(f1, f2), is(false));

    // make sure nexus has the right content after metadata cache expires
    final File a2 = downloadFile(new URL(getNexusTestRepoUrl() + "/artifacts.xml"),
            "target/downloads/nxcm1995/2/artifacts.xml");
    assertThat(a2, exists());
    assertThat(a2, not(contains("com.adobe.flexbuilder.multisdk")));
    assertThat(a2, contains("com.sonatype.nexus.p2.its.feature2"));

    assertThat(FileTestingUtils.compareFileSHA1s(a1, a2), is(false));
}