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.apache.avalon.fortress.tools.FortressBean.java

/**
 * @see org.apache.avalon.framework.activity.Disposable#dispose()
 *//*from w  w  w  .j  a v a2  s.  c o  m*/
public void dispose() {
    // Properly clean up when we are done
    org.apache.avalon.framework.container.ContainerUtil.dispose(cm);
    disposeCommonsLogging();
    //system exit, in case we were running some GUI and some thread is still active
    if (this.systemExitOnDispose) {
        Thread.yield();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            //ignore
        }

        System.exit(0);
    }
}

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

protected static Response checkAndPutValuePB(String url, String table, String row, String column,
        String valueToCheck, String valueToPut, HashMap<String, String> otherCells) throws IOException {
    RowModel rowModel = new RowModel(row);
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(valueToPut)));

    if (otherCells != null) {
        for (Map.Entry<String, String> entry : otherCells.entrySet()) {
            rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
        }//from  www  .  j av  a2 s  .c  o  m
    }

    // This Cell need to be added as last cell.
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(valueToCheck)));

    CellSetModel cellSetModel = new CellSetModel();
    cellSetModel.addRow(rowModel);
    Response response = client.put(url, Constants.MIMETYPE_PROTOBUF, cellSetModel.createProtobufOutput());
    Thread.yield();
    return response;
}

From source file:com.nokia.dempsy.TestDempsy.java

public void runAllCombinations(String applicationContext, Checker checker) throws Throwable {
    int runCount = 0;
    for (String clusterManager : clusterManagers) {
        for (String[] alternatingTransports : transports) {
            // select one of the alternatingTransports
            String transport = alternatingTransports[runCount % alternatingTransports.length];

            // alternate the dempsy configs
            String dempsyConfig = dempsyConfigs[runCount % dempsyConfigs.length];

            if (!badCombos.contains(new ClusterId(clusterManager, transport))) {
                try {
                    logger.debug("*****************************************************************");
                    logger.debug(" test: " + (checker == null ? "none" : checker) + " using " + dempsyConfig
                            + "," + clusterManager + "," + transport);
                    logger.debug("*****************************************************************");

                    DefaultRoutingStrategy.resetOutboundsChecking();

                    String[] ctx = new String[4];
                    ctx[0] = dempsyConfig;
                    ctx[1] = clusterManager;
                    ctx[2] = transport;/* ww w.j a  va 2s.co m*/
                    ctx[3] = "testDempsy/" + applicationContext;

                    logger.debug("Starting up the appliction context ...");
                    ClassPathXmlApplicationContext actx = new ClassPathXmlApplicationContext(ctx);
                    actx.registerShutdownHook();

                    Dempsy dempsy = (Dempsy) actx.getBean("dempsy");

                    assertTrue(TestUtils.waitForClustersToBeInitialized(baseTimeoutMillis, 20, dempsy));

                    WaitForShutdown waitingForShutdown = new WaitForShutdown(dempsy);
                    Thread waitingForShutdownThread = new Thread(waitingForShutdown, "Waiting For Shutdown");
                    waitingForShutdownThread.start();
                    Thread.yield();

                    logger.debug("Running test ...");
                    if (checker != null)
                        checker.check(actx);
                    logger.debug("Done with test, stopping the application context ...");

                    actx.stop();
                    actx.destroy();

                    assertTrue(waitingForShutdown.waitForShutdownDoneLatch.await(baseTimeoutMillis,
                            TimeUnit.MILLISECONDS));
                    assertTrue(waitingForShutdown.shutdown);

                    logger.debug("Finished this pass.");
                } catch (AssertionError re) {
                    logger.error("***************** FAILED ON: " + clusterManager + ", " + transport);
                    throw re;
                }

                runCount++;
            }
        }
    }
}

From source file:org.sonatype.nexus.test.booter.EmbeddedNexusBooter.java

@Override
public void stopNexus() throws Exception {
    try {//w  w w  . j a v  a2s  .co  m
        log.info("Stopping Nexus");

        if (launcher != null) {
            launcherClass.getMethod("destroy").invoke(launcher);
        }
        launcher = null;
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IllegalStateException) {
            log.debug("Ignoring", cause);
        } else {
            log.error("Stop failed", cause);
            throw Throwables.propagate(cause);
        }
    } finally {
        try {
            // The JVM caches URLs along with their current URL handler in a couple of static maps.
            // This causes unexpected issues when restarting legacy tests (even when using isolated
            // classloaders) because the cached handler persists across the restart and still refers
            // to the now shutdown framework. Felix has a few tricks to workaround this, but these
            // are defeated by the isolated legacy test classloader as the new framework cannot see
            // the old handler classes to reflectively update them.

            // (the other solution would be to not shutdown the framework when running legacy tests,
            // this would keep the old URL handlers alive at the cost of a few additional resources)

            Class<?> jarFileFactoryClass = Class.forName("sun.net.www.protocol.jar.JarFileFactory");
            Field fileCacheField = jarFileFactoryClass.getDeclaredField("fileCache");
            Field urlCacheField = jarFileFactoryClass.getDeclaredField("urlCache");
            fileCacheField.setAccessible(true);
            urlCacheField.setAccessible(true);
            ((Map<?, ?>) fileCacheField.get(null)).clear();
            ((Map<?, ?>) urlCacheField.get(null)).clear();
        } catch (Exception e) {
            log.warn("Unable to clear URL cache", e);
        }

        Thread.yield();
        System.gc();
    }
}

From source file:phex.util.FileUtils.java

/**
 * This method performce a multi fallback file rename operation to try to
 * work around the Java problems with rename operations.
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298
 *
 * @throws FileHandlingException//from ww w  . j  av  a  2  s .c o  m
 */
public static void renameFileMultiFallback(File sourceFile, File destFile) throws FileHandlingException {
    if (destFile.exists()) {
        // cant rename to file that already exists
        throw new FileHandlingException(FileHandlingException.FILE_ALREADY_EXISTS);
    }
    if (!sourceFile.exists()) {
        return;
    }

    boolean succ = sourceFile.renameTo(destFile);
    if (succ) {
        NLogger.warn(FileUtils.class, "First renameTo operation worked!");
        return;
    }
    NLogger.warn(FileUtils.class, "First renameTo operation failed.");
    // Try to run garbage collector to make the file rename operation work
    System.gc();
    // Yield thread and to hope GC kicks in...
    Thread.yield();
    // Try rename again...
    succ = sourceFile.renameTo(destFile);
    if (succ) {
        return;
    }
    NLogger.warn(FileUtils.class, "Second renameTo operation failed.");
    // Rename failed again... just perform a slow copy/delete operation
    FileInputStream input = null;
    FileOutputStream output = null;
    try {
        input = new FileInputStream(sourceFile);
        output = new FileOutputStream(destFile);
        long lengthLeft = sourceFile.length();
        byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)];
        int read;
        while (lengthLeft > 0) {
            read = input.read(buffer);
            if (read == -1) {
                break;
            }
            lengthLeft -= read;
            output.write(buffer, 0, read);
        }
    } catch (IOException exp) {
        NLogger.warn(FileUtils.class, "Third renameTo operation failed.");
        throw new FileHandlingException(FileHandlingException.RENAME_FAILED, exp);
    } finally {
        IOUtil.closeQuietly(input);
        IOUtil.closeQuietly(output);
    }
    //file copy should preserve file date
    destFile.setLastModified(sourceFile.lastModified());

    // try to delete file
    FileUtils.deleteFileMultiFallback(sourceFile);
}

From source file:phex.utils.FileUtils.java

/**
 * This method performce a multi fallback file rename operation to try to 
 * work around the Java problems with rename operations.
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298
 * @throws FileHandlingException //from  w  ww . j a  va2  s  .c  om
 */
public static void renameFileMultiFallback(File sourceFile, File destFile) throws FileHandlingException {
    if (destFile.exists()) {
        // cant rename to file that already exists
        throw new FileHandlingException(FileHandlingException.FILE_ALREADY_EXISTS);
    }
    if (!sourceFile.exists()) {
        return;
    }

    boolean succ = sourceFile.renameTo(destFile);
    if (succ) {
        //NLogger.warn( FileUtils.class, "First renameTo operation worked!" );
        return;
    }
    //NLogger.warn( FileUtils.class, "First renameTo operation failed." );
    // Try to run garbage collector to make the file rename operation work
    System.gc();
    // Yield thread and to hope GC kicks in...
    Thread.yield();
    // Try rename again...
    succ = sourceFile.renameTo(destFile);
    if (succ) {
        return;
    }
    //NLogger.warn( FileUtils.class, "Second renameTo operation failed." );
    // Rename failed again... just perform a slow copy/delete operation
    FileInputStream input = null;
    FileOutputStream output = null;
    try {
        input = new FileInputStream(sourceFile);
        output = new FileOutputStream(destFile);
        long lengthLeft = sourceFile.length();
        byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)];
        int read;
        while (lengthLeft > 0) {
            read = input.read(buffer);
            if (read == -1) {
                break;
            }
            lengthLeft -= read;
            output.write(buffer, 0, read);
        }
    } catch (IOException exp) {
        //NLogger.warn( FileUtils.class, "Third renameTo operation failed." );
        throw new FileHandlingException(FileHandlingException.RENAME_FAILED, exp);
    } finally {
        IOUtil.closeQuietly(input);
        IOUtil.closeQuietly(output);
    }
    //file copy should preserve file date
    destFile.setLastModified(sourceFile.lastModified());

    // try to delete file
    FileUtils.deleteFileMultiFallback(sourceFile);
}

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

private static Response checkAndPutValuePB(String url, String table, String row, String column,
        String valueToCheck, String valueToPut) throws IOException {
    RowModel rowModel = new RowModel(row);
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(valueToPut)));
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(valueToCheck)));
    CellSetModel cellSetModel = new CellSetModel();
    cellSetModel.addRow(rowModel);/*from   w w  w .  jav a 2s .  c  om*/
    Response response = client.put(url, Constants.MIMETYPE_PROTOBUF, cellSetModel.createProtobufOutput());
    Thread.yield();
    return response;
}

From source file:org.apache.streams.hdfs.WebHdfsPersistReader.java

protected void write(StreamsDatum entry) {
    boolean success;
    do {/*from  w w w . ja  v a 2s  .  com*/
        synchronized (WebHdfsPersistReader.class) {
            success = persistQueue.offer(entry);
        }
        Thread.yield();
    } while (!success);
}

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

void doTestSingleCellGetPutBinary() throws IOException {
    final String path = "/" + TABLE + "/" + ROW_3 + "/" + COLUMN_1;
    final byte[] body = Bytes.toBytes(VALUE_3);
    Response response = client.put(path, MIMETYPE_BINARY, body);
    assertEquals(response.getCode(), 200);
    Thread.yield();

    response = client.get(path, MIMETYPE_BINARY);
    assertEquals(response.getCode(), 200);
    assertTrue(Bytes.equals(response.getBody(), body));
    boolean foundTimestampHeader = false;
    for (Header header : response.getHeaders()) {
        if (header.getName().equals("X-Timestamp")) {
            foundTimestampHeader = true;
            break;
        }/*from   ww w.j  a v  a2 s.c o m*/
    }
    assertTrue(foundTimestampHeader);

    response = deleteRow(TABLE, ROW_3);
    assertEquals(response.getCode(), 200);
}

From source file:org.polymap.core.runtime.UIJob.java

/**
 * Waits until this job is finished. This method will block the calling thread
 * until the job has finished executing, or until this thread has been
 * interrupted, or the timeout exceeds. A job must not be joined from within the
 * scope of its run method.//from w w w .j a va2s.c  o m
 * <p/>
 * This method must be called from the UIThread. It calls readAndDispatch() of
 * the current display, so that the UI is responsive during the call is blocked.
 * 
 * @param timeoutMillis
 * @return False if the job did not finish within the given timeout or the
 *         calling thread was interrupted.
 */
public boolean joinAndDispatch(long timeoutMillis) {

    final AtomicBoolean done = new AtomicBoolean(getState() == Job.NONE);

    IJobChangeListener jobListener = new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {
            synchronized (done) {
                done.set(true);
                done.notify();
            }
        }
    };
    addJobChangeListener(jobListener);

    // check if job is done already - after the listener has been
    // registered; this avoids race cond. between the two
    if (getState() == Job.NONE) {
        removeJobChangeListener(jobListener);
        return true;
    }

    final Display threadDisplay = Display.getCurrent();
    final Timer timer = new Timer();
    while (!done.get() && timer.elapsedTime() < timeoutMillis
            && (threadDisplay == null || !threadDisplay.isDisposed())) {

        Thread.yield();
        if (threadDisplay != null) {
            if (!threadDisplay.readAndDispatch()) {
                synchronized (done) {
                    try {
                        done.wait(300);
                        log.debug("wake after: " + timer.elapsedTime() + "ms");
                    } catch (InterruptedException e) {
                    }
                }
                //                    // just wait on #done blocks hangs;
                //                    // display.sleep() might wait forever, so we need this watchdog
                //                    Polymap.executorService().execute( new Runnable() {
                //                        public void run() {
                //                            synchronized (done) {
                //                                try { done.wait( 300 ); } catch (InterruptedException e) {}
                //                            }
                //                            log.info( "wake ..." );
                //                            threadDisplay.wake();
                //                        }
                //                    });
                //                    threadDisplay.sleep();
            }
        } else {
            synchronized (done) {
                try {
                    done.wait(250);
                } catch (InterruptedException e) {
                }
            }
        }
    }
    removeJobChangeListener(jobListener);
    return done.get();
}