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.callidusrobotics.swing.SwingConsole.java

@Override
public void render() {
    if (refreshSet.size() == 0) {
        return;/*w  ww . ja  v a 2 s . com*/
    }

    while (System.currentTimeMillis() - lastUpdate < REFRESH_RATE) {
        Thread.yield();
    }

    final Iterator<Integer> iterator = refreshSet.iterator();
    while (iterator.hasNext()) {
        final int index = iterator.next();

        // index = r * cols + c
        final int row = index / getWidth();
        final int col = index % getWidth();

        final int hpos = col * charWidth;
        final int vpos = row * charHeight;

        graphicsRenderer.setColor(consoleBuffer[row][col].background);
        graphicsRenderer.fillRect(hpos, vpos, charWidth, charHeight);
        graphicsRenderer.setColor(consoleBuffer[row][col].foreground);
        graphicsRenderer.drawString(String.valueOf(consoleBuffer[row][col].character), hpos + charHOffset,
                vpos + charVOffset);
    }
    refreshSet.clear();

    if (cursorIsVisible) {
        final int hpos = cursorCol * charWidth;
        final int vpos = cursorRow * charHeight;

        graphicsRenderer.setColor(cursor.foreground);
        graphicsRenderer.drawString(String.valueOf(cursor.character), hpos + charHOffset, vpos + charVOffset);
    }

    graphicsRenderer.drawImage(imageBuffer, 0, 0, null);
    icon.setImage(imageBuffer);
    label.setVisible(false);
    label.setVisible(true);

    lastUpdate = System.currentTimeMillis();
}

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

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

    try {//from  w w w  . j  a  va2 s .c om
        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));

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

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

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

private static Response deleteValue(String table, String row, String column) throws IOException {
    StringBuilder path = new StringBuilder();
    path.append('/');
    path.append(table);// w  ww.j  a va  2  s.co m
    path.append('/');
    path.append(row);
    path.append('/');
    path.append(column);
    Response response = client.delete(path.toString());
    Thread.yield();
    return response;
}

From source file:com.flowpowered.commons.ticking.Timer.java

/**
 * An accurate sync method that will attempt to run at the tps. It should be called once every tick.
 *//*from  w ww.  j  a  v a2 s  .  c o m*/
public void sync() {
    if (nextTick < 0) {
        throw new IllegalStateException("Timer was not started");
    }
    if (tps <= 0) {
        return;
    }
    try {
        // Sleep until the average sleep time is greater than the time remaining until next tick
        for (long time1 = getTime(), time2; nextTick - time1 > sleepDurations.average(); time1 = time2) {
            Thread.sleep(1);
            // Update average sleep time
            sleepDurations.add((time2 = getTime()) - time1);
        }
        // Slowly dampen sleep average if too high to avoid yielding too much
        sleepDurations.dampen();
        // Yield until the average yield time is greater than the time remaining until next tick
        for (long time1 = getTime(), time2; nextTick - time1 > yieldDurations.average(); time1 = time2) {
            Thread.yield();
            // Update average yield time
            yieldDurations.add((time2 = getTime()) - time1);
        }
    } catch (InterruptedException ignored) {
    }
    // Schedule next frame, drop frames if it's too late for next frame
    nextTick = Math.max(nextTick + 1000000000 / tps, getTime());
}

From source file:com.varaneckas.hawkscope.hotkey.X11HotkeyListener.java

/**
 * Displays Hawkscope menu at mouse location. Based on dirty hacks and 
 * blind experiments. Basically, it creates a window beneath the cursor
 * and executes a real mouse click with help of {@link Robot}. This way
 * invoking the menu works.// w w w  .  j  a  va2s .  c  o m
 * 
 * A bug that prevents the normal activity:
 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=11570
 */
protected void displayHawkscopeMenu() {
    try {
        MenuFactory.getMainMenu().getSwtMenuObject().getDisplay().syncExec(new Runnable() {
            public void run() {
                if (MenuFactory.getMainMenu().getSwtMenuObject().isVisible()) {
                    MenuFactory.getMainMenu().forceHide();
                }
                try {
                    final StateEvent se = new StateEvent();
                    final Point loc = Display.getDefault().getCursorLocation();
                    se.setX(loc.x);
                    se.setY(loc.y);
                    hawkscopeLaunchShell.setLocation(loc.x - 30, loc.y - 30);
                    hawkscopeLaunchShell.setSize(60, 60);
                    hawkscopeLaunchShell.setVisible(true);
                    //for a weird reason, if the second shell is not
                    //displayed, the whole hack does not work.
                    supportShell.setLocation(loc.x - 30, loc.y - 30);
                    supportShell.setSize(60, 60);
                    supportShell.setVisible(true);
                    //need all the sleeps
                    //if duration is lowered, hack starts to randomly
                    //fail to work.
                    Thread.sleep(50L);
                    Thread.yield();
                    if (robo != null) {
                        robo.mousePress(InputEvent.BUTTON1_MASK);
                        Thread.sleep(50L);
                    }
                    MenuFactory.getMainMenu().getState().act(se);
                    Thread.sleep(50L);
                    if (robo != null) {
                        robo.mouseRelease(InputEvent.BUTTON1_MASK);
                    }
                    supportShell.setVisible(false);
                    hawkscopeLaunchShell.setVisible(false);
                } catch (final Exception e) {
                    throw new RuntimeException("Failed invoking hawkscope " + "menu with shortcut", e);
                }
            }
        });
    } catch (final Exception e) {
        throw new RuntimeException("Failed invoking hawkscope with " + "shortcut key", e);
    }
}

From source file:com.indeed.lsmtree.recordlog.TestBlockCompressedRecordFile.java

public void testRandom() throws IOException {
    final BlockCompressedRecordFile<String> recordFile = createBlockCache();
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < 8; i++) {
        final int index = i;
        new Thread(new Runnable() {
            @Override//from   ww w .j a  va  2  s.  c om
            public void run() {
                try {
                    final Random r = new Random(index);
                    for (int i = 0; i < 10000000; i++) {
                        int rand = r.nextInt(positions.size());
                        assertTrue(recordFile.get(positions.get(rand)).equals(strings.get(rand)));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    recordFile.close();
}

From source file:blue.ui.core.render.ProcessConsole.java

private void execWaitAndCollect(String commandLine, File currentWorkingDirectory) throws IOException {
    try {/*from  w  w w .  j a  v a 2 s  .c  o  m*/
        exec(commandLine, currentWorkingDirectory, true);
        process.waitFor();

        while ((stderrThread != null && stderrThread.isCollecting)
                || (stdoutThread != null && stdoutThread.isCollecting)) {
            Thread.yield();
            Thread.sleep(50);
        }

        destroy(true, false);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

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

Response deleteValue(String table, String row, String column) throws IOException {
    StringBuilder path = new StringBuilder();
    path.append('/');
    path.append(table);//  w w w . j a  va  2s.  c  o m
    path.append('/');
    path.append(row);
    path.append('/');
    path.append(column);
    Response response = client.delete(path.toString());
    Thread.yield();
    return response;
}

From source file:net.lightbody.bmp.proxy.jetty.http.nio.SocketChannelOutputStream.java

private void flushBuffer() throws IOException {
    while (_flush.hasRemaining()) {
        int len = _channel.write(_flush);
        if (len < 0)
            throw new IOException("EOF");
        if (len == 0) {
            // write channel full.  Try letting other threads have a go.
            Thread.yield();
            len = _channel.write(_flush);
            if (len < 0)
                throw new IOException("EOF");
            if (len == 0) {
                // still full.  need to  block until it is writable.
                if (_selector == null) {
                    _selector = Selector.open();
                    _channel.register(_selector, SelectionKey.OP_WRITE);
                }/*from w  w  w . ja v  a2 s . c  o  m*/

                _selector.select();
            }
        }
    }
}