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

public void run() {
    // Set up Graphics context
    gc = canvas.getGraphicsContext3D();//  w w w  . j  av  a 2s . c o m

    // We always need to set this for PureImmediate
    // stereo mode
    gc.setBufferOverride(true);

    Color3f lightColor = new Color3f(1, 1, 1);
    Vector3f lightDir = new Vector3f(0, 0, -1);
    DirectionalLight light = new DirectionalLight(lightColor, lightDir);

    gc.addLight(light);

    Appearance redApp = new Appearance();
    Appearance greenApp = new Appearance();
    Color3f ambientColor = new Color3f(0, 0, 0);
    Color3f emissiveColor = new Color3f(0, 0, 0);
    Color3f diffuseColor = new Color3f(1, 0, 0);
    Color3f specularColor = new Color3f(1, 1, 1);
    redApp.setMaterial(new Material(ambientColor, emissiveColor, diffuseColor, specularColor, 5));
    diffuseColor = new Color3f(0, 1, 0);

    greenApp.setMaterial(new Material(ambientColor, emissiveColor, diffuseColor, specularColor, 5));

    // Set up geometry
    Cone leftCone = new Cone(0.4f, 0.6f, Primitive.GENERATE_NORMALS, redApp);
    Cone rightCone = new Cone(0.4f, 0.6f, Primitive.GENERATE_NORMALS, greenApp);
    leftConeBody = leftCone.getShape(Cone.BODY);
    leftConeCap = leftCone.getShape(Cone.CAP);

    rightConeBody = rightCone.getShape(Cone.BODY);
    rightConeCap = rightCone.getShape(Cone.CAP);
    leftTrans = new Vector3f(-0.6f, 0, 0);
    rightTrans = new Vector3f(0.6f, 0, 0);

    while (true) {
        // compute data which is can be used
        // for both left and right eye
        computeSharedData();

        if (stereoSupport) {
            if (!sharedStereoZbuffer) {
                gc.setStereoMode(GraphicsContext3D.STEREO_BOTH);
                // This clear both left and right buffers, we
                // must set STEREO_BOTH before it. Otherwise
                // it only clear LEFT or RIGHT buffer unless
                // this is invoke twice for each buffer.
                gc.clear();
            }

            gc.setStereoMode(GraphicsContext3D.STEREO_LEFT);
            renderLeft();

            gc.setStereoMode(GraphicsContext3D.STEREO_RIGHT);
            renderRight();
        } else {
            gc.clear();
            renderLeft();
        }

        // This swap both left and right buffers so
        // there is no need to set STEREO_BOTH before it
        canvas.swap();

        // Be polite to other threads !
        Thread.yield();
    }
}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

public void testRoundTripMultiPart() throws Exception {

    String msgId = UUIDGenerator.getUUID();
    Options options = new Options();
    options.setTo(new EndpointReference("mailto:synapse.test.6@gmail.com"));
    options.setReplyTo(new EndpointReference("mailto:synapse.test.0@gmail.com"));
    options.setAction(Constants.AXIS2_NAMESPACE_URI + "/echoOMElement");
    options.setMessageId(msgId);//from w  w  w  .j  a  v a  2 s .  c  o m

    options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT, MailConstants.TRANSPORT_FORMAT_MP);

    ServiceClient sender = new ServiceClient(getClientCfgCtx(), null);
    sender.setOptions(options);
    sender.fireAndForget(createPayload());

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

    Object reply = null;
    boolean replyNotFound = true;
    int retryCount = 3;
    while (replyNotFound) {
        log.debug("Checking for response ... with MessageID : " + msgId);
        reply = getMessage(msgId);
        if (reply != null) {
            replyNotFound = false;
        } else {
            if (retryCount-- > 0) {
                Thread.sleep(10000);
            } else {
                break;
            }
        }
    }

    if (reply != null && reply instanceof String) {
        log.debug("Result Body : " + reply);
        XMLStreamReader reader = StAXUtils.createXMLStreamReader(new StringReader((String) reply));
        SOAPEnvelope env = new StAXSOAPModelBuilder(reader).getSOAPEnvelope();
        if (env != null) {
            AXIOMXPath xpath = new AXIOMXPath("//my:myValue");
            xpath.addNamespace("my", "http://localhost/axis2/services/EchoXMLService");
            Object result = xpath.evaluate(env);
            if (result != null && result instanceof OMElement) {
                assertEquals("omTextValue", ((OMElement) result).getText());
            }
        }
    } else {
        fail("Did not receive the reply mail");
    }
}

From source file:org.apache.zeppelin.notebook.NotebookTest.java

@Test
public void testClearParagraphOutput() throws IOException, SchedulerException {
    Note note = notebook.createNote();//from   w  w  w.  j a  v  a2s. c o  m
    Paragraph p1 = note.addParagraph();
    p1.setText("hello world");
    note.run(p1.getId());

    while (p1.isTerminated() == false || p1.getResult() == null)
        Thread.yield();
    assertEquals("repl1: hello world", p1.getResult().message());

    // clear paragraph output/result
    note.clearParagraphOutput(p1.getId());
    assertNull(p1.getResult());
}

From source file:com.yek.keyboard.ChewbaccaUncaughtExceptionHandler.java

public void uncaughtException(Thread thread, Throwable ex) {
    ex.printStackTrace();/*from   ww w.j a v a  2  s .co  m*/
    Logger.e(TAG, "Caught an unhandled exception!!!", ex);
    boolean ignore = false;

    // https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/15
    //https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/433
    String stackTrace = Logger.getStackTrace(ex);
    if (ex instanceof NullPointerException) {
        if (stackTrace.contains(
                "android.inputmethodservice.IInputMethodSessionWrapper.executeMessage(IInputMethodSessionWrapper.java")
                || stackTrace.contains(
                        "android.inputmethodservice.IInputMethodWrapper.executeMessage(IInputMethodWrapper.java")) {
            Logger.w(TAG, "An OS bug has been adverted. Move along, there is nothing to see here.");
            ignore = true;
        }
    } else if (ex instanceof java.util.concurrent.TimeoutException) {
        if (stackTrace.contains(".finalize")) {
            Logger.w(TAG, "An OS bug has been adverted. Move along, there is nothing to see here.");
            ignore = true;
        }
    }

    if (!ignore && AnyApplication.getConfig().useChewbaccaNotifications()) {
        String appName = DeveloperUtils.getAppDetails(mApp);

        final CharSequence utcTimeDate = DateFormat.format("kk:mm:ss dd.MM.yyyy", new Date());
        final String newline = DeveloperUtils.NEW_LINE;
        String logText = "Hi. It seems that we have crashed.... Here are some details:" + newline
                + "****** UTC Time: " + utcTimeDate + newline + "****** Application name: " + appName + newline
                + "******************************" + newline + "****** Exception type: "
                + ex.getClass().getName() + newline + "****** Exception message: " + ex.getMessage() + newline
                + "****** Trace trace:" + newline + stackTrace + newline;
        logText += "******************************" + newline + "****** Device information:" + newline
                + DeveloperUtils.getSysInfo(mApp);
        if (ex instanceof OutOfMemoryError
                || (ex.getCause() != null && ex.getCause() instanceof OutOfMemoryError)) {
            logText += "******************************\n" + "****** Memory:" + newline + getMemory();
        }

        if (ex instanceof Resources.NotFoundException) {
            int resourceId = extractResourceIdFromException((Resources.NotFoundException) ex);
            logText += "******************************\n";
            if (resourceId == 0) {
                logText += "Failed to extract resource id from message\n";
            } else {
                String possibleResources = getResourcesNamesWithValue(resourceId);
                if (TextUtils.isEmpty(possibleResources)) {
                    logText += "Could not find matching resources for resource id " + resourceId
                            + ", this may happen if the resource is from an external package.\n";
                } else {
                    logText += "Possible resources for " + resourceId + ":\n";
                }

            }
            logText += "******************************\n";
        }
        logText += "******************************" + newline + "****** Log-Cat:" + newline
                + Logger.getAllLogLines();

        String crashType = ex.getClass().getSimpleName() + ": " + ex.getMessage();
        Intent notificationIntent = new Intent(mApp, SendBugReportUiActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        final Parcelable reportDetailsExtra = new SendBugReportUiActivity.BugReportDetails(ex, logText);
        notificationIntent.putExtra(SendBugReportUiActivity.EXTRA_KEY_BugReportDetails, reportDetailsExtra);

        PendingIntent contentIntent = PendingIntent.getActivity(mApp, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(mApp);
        builder.setSmallIcon(
                Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? R.drawable.notification_error_icon
                        : R.drawable.ic_notification_error)
                .setColor(ContextCompat.getColor(mApp, R.color.notification_background_error))
                .setTicker(mApp.getText(R.string.ime_crashed_ticker))
                .setContentTitle(mApp.getText(R.string.ime_name))
                .setContentText(mApp.getText(R.string.ime_crashed_sub_text))
                .setSubText(BuildConfig.TESTING_BUILD ? crashType
                        : null/*not showing the type of crash in RELEASE mode*/)
                .setWhen(System.currentTimeMillis()).setContentIntent(contentIntent).setAutoCancel(true)
                .setOnlyAlertOnce(true).setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

        // notifying
        NotificationManager notificationManager = (NotificationManager) mApp
                .getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(R.id.notification_icon_app_error, builder.build());
    }
    // and sending to the OS
    if (!ignore && mOsDefaultHandler != null) {
        Logger.i(TAG, "Sending the exception to OS exception handler...");
        mOsDefaultHandler.uncaughtException(thread, ex);
    }

    Thread.yield();
    //halting the process. No need to continue now. I'm a dead duck.
    System.exit(0);
}

From source file:com.xerox.amazonws.sdb.Domain.java

/**
 * Gets attributes of given items. This method threads off the get requests and
 * aggregates the responses.//from   www. j av a  2 s .c  om
 *
 * @param items the list of items to get attributes for
  * @return the map of items with lists of attributes
 * @throws SDBException wraps checked exceptions
 */
public Map<String, List<ItemAttribute>> getItemsAttributes(List<String> items) throws SDBException {
    Map<String, List<ItemAttribute>> results = new Hashtable<String, List<ItemAttribute>>();
    ThreadPoolExecutor pool = getThreadPoolExecutor();
    pool.setRejectedExecutionHandler(new RejectionHandler());

    Counter running = new Counter(0);
    for (String item : items) {
        while (pool.getActiveCount() == pool.getMaximumPoolSize()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
        }
        synchronized (running) {
            running.increment();
        }
        pool.execute(new AttrWorker(getItem(item), running, results, null));
        Thread.yield();
    }
    while (true) {
        if (running.getValue() == 0) {
            break;
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
        }
    }
    if (this.executor == null) {
        pool.shutdown();
    }
    return results;
}

From source file:org.apache.http.benchmark.HttpBenchmark.java

public String execute() throws Exception {

    prepare();/* ww w.  jav  a2 s .  c  o  m*/

    ThreadPoolExecutor workerPool = new ThreadPoolExecutor(config.getThreads(), config.getThreads(), 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                public Thread newThread(Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()];
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new BenchmarkWorker(params, config.getVerbosity(), request[i], host, config.getRequests(),
                config.isKeepAlive(), config.isDisableSSLVerification(), config.getTrustStorePath(),
                config.getTrustStorePassword(), config.getIdentityStorePath(),
                config.getIdentityStorePassword());
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < config.getThreads()) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }

    workerPool.shutdown();
    return ResultProcessor.printResults(workers, host, config.getUrl().toString(), contentLength);
}

From source file:com.auditbucket.test.functional.TestForceDeadlock.java

private void doFutureWorked(Future<Integer> future, int count) throws Exception {
    while (!future.isDone()) {
        Thread.yield();
    }/*  ww  w  .j  ava2  s .  co m*/
    assertEquals(count, future.get().intValue());

}

From source file:net.lightbody.bmp.proxy.jetty.util.Pool.java

public void stop() throws InterruptedException {
    synchronized (this) {
        _running--;//from w  ww  . jav  a2  s .com
        if (_running > 0)
            return;
        notifyAll();
    }

    if (_pondLife != null && _size > 0) {
        for (int i = 0; i < _pondLife.length; i++)
            closePondLife(i);
        Thread.yield();
        for (int i = 0; i < _pondLife.length; i++)
            stopPondLife(i);
    }

    synchronized (this) {
        _pondLife = null;
        _index = null;
        _size = 0;
        _available = 0;
    }
}

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

protected static Response putValueXML(String url, String table, String row, String column, String value)
        throws IOException, JAXBException {
    RowModel rowModel = new RowModel(row);
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value)));
    CellSetModel cellSetModel = new CellSetModel();
    cellSetModel.addRow(rowModel);//from w w w.j ava  2  s .  c  om
    StringWriter writer = new StringWriter();
    xmlMarshaller.marshal(cellSetModel, writer);
    Response response = client.put(url, Constants.MIMETYPE_XML, Bytes.toBytes(writer.toString()));
    Thread.yield();
    return response;
}

From source file:jetbrains.exodus.gc.GarbageCollector.java

@SuppressWarnings("OverlyLongMethod")
public /* public access is necessary to invoke the method from the Reflect class */
boolean doCleanFile(final long fileAddress) {
    // the file may be already cleaned
    if (isFileToBeDeleted(fileAddress)) {
        return false;
    }//from  w  w  w . j av a 2 s  .  c  o m
    loggingInfo("start cleanFile(" + env.getLocation() + File.separatorChar
            + LogUtil.getLogFilename(fileAddress) + ')');
    // At first, we clone whole meta tree inside of 'begin transaction'
    // in order to save it completely on commit of transaction.
    // Thus we can ignore all loggables belonging to the meta tree.
    final TransactionImpl txn = env.beginTransactionWithClonedMetaTree();
    try {
        final Log log = getLog();
        if (logging.isDebugEnabled()) {
            final long high = log.getHighAddress();
            final long highFile = log.getHighFileAddress();
            logging.debug(String.format(
                    "Cleaner acquired txn when log high address was: %d (%s@%d) when cleaning file %s", high,
                    LogUtil.getLogFilename(highFile), high - highFile, LogUtil.getLogFilename(fileAddress)));
        }
        final long nextFileAddress = log.getNextFileAddress(fileAddress);
        final Iterator<RandomAccessLoggable> loggables = log.getLoggableIterator(fileAddress);
        while (loggables.hasNext()) {
            final RandomAccessLoggable loggable = loggables.next();
            if (nextFileAddress != Loggable.NULL_ADDRESS && loggable.getAddress() >= nextFileAddress) {
                break;
            }
            final int structureId = loggable.getStructureId();
            if (structureId != Loggable.NO_STRUCTURE_ID && structureId != EnvironmentImpl.META_TREE_ID) {
                StoreImpl store = openStoresCache.get(structureId);
                if (store == null) {
                    // TODO: remove openStoresCache when txn.openStoreByStructureId() is fast enough (XD-381)
                    store = txn.openStoreByStructureId(structureId);
                    openStoresCache.put(structureId, store);
                }
                store.reclaim(txn, loggable, loggables, expirationChecker);
            }
        }
        if (!txn.forceFlush()) {
            Thread.yield();
            return false;
        }
    } catch (Throwable e) {
        logging.error("cleanFile(" + LogUtil.getLogFilename(fileAddress) + ')', e);
        throw ExodusException.toExodusException(e);
    } finally {
        txn.abort();
    }
    pendingFilesToDelete.add(fileAddress);
    env.executeTransactionSafeTask(new Runnable() {
        @Override
        public void run() {
            deletionQueue.offer(fileAddress);
        }
    });
    return true;
}