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.artifactory.maven.index.RepoIndexer.java

@Override
public void artifactDiscovered(ArtifactContext ac) {
    if (log.isTraceEnabled()) {
        log.trace("Artifact discovered: '{}'", ac.getArtifactInfo().getUinfo());
    }//ww w.  j a  va 2s.  co m
    if (TaskUtils.pauseOrBreak()) {
        throw new TaskInterruptedException();
    }
    //Be nice with other threads
    Thread.yield();
}

From source file:com.vinay.simpleadserver.cache.AdServerInMemoryCache.java

/**
 * cleanup() method is periodically called to remove key/value pairs that
 * have expired from the cache.// w w  w.  j  a va 2  s.c o  m
 */
@SuppressWarnings("unchecked")
public void cleanup() {

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

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

        deleteKey = new ArrayList<>((adServerCacheMap.size() / 2) + 1);
        K key = null;
        AdServerCacheObject c = null;

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

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

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

        Thread.yield();
    }
}

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

public void testRoundTripPOX() throws Exception {

    String msgId = UUIDGenerator.getUUID();

    Session session = Session.getInstance(props, new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("synapse.test.1", "mailpassword");
        }/*from w  w  w.j a  v a  2s.c  om*/
    });
    session.setDebug(log.isTraceEnabled());

    WSMimeMessage msg = new WSMimeMessage(session);
    msg.setFrom(new InternetAddress("synapse.test.0@gmail.com"));
    msg.setReplyTo(InternetAddress.parse("synapse.test.0@gmail.com"));
    InternetAddress[] address = { new InternetAddress("synapse.test.6@gmail.com") };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("POX Roundtrip");
    msg.setHeader(BaseConstants.SOAPACTION, Constants.AXIS2_NAMESPACE_URI + "/echoOMElement");
    msg.setSentDate(new Date());
    msg.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgId);
    msg.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgId);
    msg.setText(POX_MESSAGE);
    Transport.send(msg);

    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));
        OMElement res = new StAXOMBuilder(reader).getDocumentElement();
        if (res != null) {
            AXIOMXPath xpath = new AXIOMXPath("//my:myValue");
            xpath.addNamespace("my", "http://localhost/axis2/services/EchoXMLService");
            Object result = xpath.evaluate(res);
            if (result != null && result instanceof OMElement) {
                assertEquals("omTextValue", ((OMElement) result).getText());
            }
        }
    } else {
        fail("Did not receive the reply mail");
    }
}

From source file:com.callidusrobotics.swing.SwingConsole.java

@Override
@SuppressWarnings("PMD.NullAssignment")
public char getKeyPress() {
    lastKeyPressed = null;// ww w. j  a  v a 2s  .c o m
    while (lastKeyPressed == null) {
        Thread.yield();
    }

    if (lastKeyPressed.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
        return (char) lastKeyPressed.getKeyCode();
    }

    return lastKeyPressed.getKeyChar();
}

From source file:com.byteatebit.nbserver.simple.SelectorTask.java

@Override
public void run() {
    long lastTaskTimeoutCheck = System.currentTimeMillis();
    while (shouldRun.get()) {
        // check for tasks without any activity in the
        // max time allowed
        if (System.currentTimeMillis() - lastTaskTimeoutCheck >= ioTaskTimeoutCheckPeriodMs) {
            handleTimedOutTasks();/*ww w  .  j  av  a2 s. c  om*/
            lastTaskTimeoutCheck = System.currentTimeMillis();
        }
        // select tasks for which the underlying channel is
        // ready for the appropriate IO operations
        try {
            if (selectorTimeoutMs < 1) {
                int numReadyKeys = selector.selectNow();
                if (numReadyKeys == 0)
                    Thread.yield();
            } else {
                selector.select(selectorTimeoutMs);
            }
        } catch (ClosedSelectorException e) {
            LOG.error("selector closed, shutting down selector task", e);
            running = false;
        } catch (Exception e) {
            LOG.error("Exception thrown while on selector.select call", e);
        }
        // execute selected tasks
        executeIoTasksOnSelectedKeys();
    }
    try {
        selector.close();
    } catch (Exception e) {
        LOG.error("Selector threw exception on close", e);
    }
    this.stopped = true;
}

From source file:com.aptana.webserver.internal.core.builtin.LocalWebServer.java

private void startServer(final InetAddress host, final int port) {
    updateState(State.STARTING);// w  w w.ja  v a  2s  .  c o m
    thread = new Thread() {
        @Override
        public void run() {
            runServer(new InetSocketAddress(host, port),
                    new BasicAsyncRequestHandler(new LocalWebServerHttpRequestHandler(LocalWebServer.this)));
        }
    };
    thread.setDaemon(true);
    thread.start();
    Thread.yield();
    long startTime = System.currentTimeMillis();
    while (thread.isAlive() && (System.currentTimeMillis() - startTime) < STARTUP_TIMEOUT) {
        if (reactor != null && reactor.getStatus() == IOReactorStatus.ACTIVE) {
            updateState(State.STARTED);
            break;
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            updateState(State.UNKNOWN);
            break;
        }
    }
}

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

public void testRandomWithReader() 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// w w w.ja  v a  2  s.co  m
            public void run() {
                try {
                    final Random r = new Random(index);
                    for (int i = 0; i < 10000000; i++) {
                        int rand = r.nextInt(positions.size());
                        final RecordFile.Reader<String> reader = recordFile.reader(positions.get(rand));
                        assertTrue(reader.next());
                        assertEquals(reader.get(), strings.get(rand));
                        reader.close();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    recordFile.close();
}

From source file:com.android.marrowbone.anysoftboard.ChewbaccaUncaughtExceptionHandler.java

public void uncaughtException(Thread thread, Throwable ex) {
    Log.e(TAG, "Caught an unhandled exception!!! ", ex);
    boolean ignore = false;

    // https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/15
    String stackTrace = Log.getStackTrace(ex);
    if (ex instanceof NullPointerException && stackTrace != null && stackTrace.contains(
            "android.inputmethodservice.IInputMethodSessionWrapper.executeMessage(IInputMethodSessionWrapper.java")) {
        // https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/15
        Log.w(TAG, "An OS bug has been adverted. Move along, there is nothing to see here.");
        ignore = true;//  ww  w .  j a  va 2s  .com
    }

    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();
        if (ex instanceof OutOfMemoryError
                || (ex.getCause() != null && ex.getCause() instanceof OutOfMemoryError)) {
            logText += "******************************\n" + "****** Memory:" + newline + getMemory();
        }
        logText += "******************************" + newline + "****** Log-Cat:" + newline
                + Log.getAllLogLines();

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

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

        NotificationCompat.Builder builder = new NotificationCompat.Builder(mApp);
        builder.setSmallIcon(R.drawable.notification_error_icon)
                .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.DEBUG ? 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(1, builder.build());
    }
    // and sending to the OS
    if (!ignore && mOsDefaultHandler != null) {
        Log.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.streamsets.lib.security.http.PasswordHasher.java

protected String computeHash(String version, int iterations, byte[] salt, String valueTohash) {
    long start = System.currentTimeMillis();
    try {//from  w ww.ja  va2  s .c o m
        // yield CPU when this method is run in a tight loop
        Thread.yield();
        PBEKeySpec spec = new PBEKeySpec(valueTohash.toCharArray(), salt, iterations, getKeyLength());
        byte[] hash = SECRET_KEY_FACTORIES.get(version).generateSecret(spec).getEncoded();
        return version + ":" + iterations + ":" + Hex.encodeHexString(salt) + ":" + Hex.encodeHexString(hash);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        LOG.trace("Computing password hash '{}' with '{}' iterations took '{}msec'", version, iterations,
                System.currentTimeMillis() - start);
    }
}

From source file:at.uni_salzburg.cs.ckgroup.apos.AposNtripCasterMock.java

/**
 * This method stops the running NTRIP caster thread
 *
 * @throws IllegalStateException thrown if the mail server does not run
 *//*  ww w  . ja va  2s . c  om*/
public void stopCasterThread() throws IllegalStateException {
    System.out.println("\nStop NTRIP Caster on port " + port);
    if (ntripCaster == null)
        throw new IllegalStateException("NTRIP caster thread does not run.");

    ntripCaster.terminate();

    // Now we wait for the NTRIP caster to diminish.
    int cycles = 100;
    while (ntripCasterRunning && --cycles > 0) {
        try {
            Thread.sleep(50);
        } catch (Exception e) {
        }
        Thread.yield();
    }

    ntripCaster = null;
}