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:uk.co.real_logic.aeron.tools.ThwackerTool.java

/**
 * Worker Thread Method:/*ww  w.jav a 2 s  .c  o  m*/
 * Randomly selects a publication, checks if it is active, then attempts to send on that publication
 */

public void sendOnRandomPub() {
    final Random rand = SeedableThreadLocalRandom.current();
    int i;
    ThwackingElement pub;
    final long threadId = Thread.currentThread().getId();

    LOG.fine("Sending thread " + threadId + " started!");
    while (running) {
        //Get random publication slot
        i = rand.nextInt(numberOfPublications);
        pub = pubs[i];
        pub.trySendMessage(threadId);
        /* Every iteration sends on the control Publication */
        ctrlPub.trySendMessage(threadId);

        Thread.yield();
    }
    allDone.countDown();
    LOG.fine("Sending thread " + threadId + " all done!");
}

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

void doTestMultiCellGetPutPB() throws IOException {
    String path = "/" + TABLE + "/fakerow"; // deliberate nonexistent row

    CellSetModel cellSetModel = new CellSetModel();
    RowModel rowModel = new RowModel(ROW_1);
    rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_1), Bytes.toBytes(VALUE_1)));
    rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_2), Bytes.toBytes(VALUE_2)));
    cellSetModel.addRow(rowModel);//from   www .j a  va2s.  com
    rowModel = new RowModel(ROW_2);
    rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_1), Bytes.toBytes(VALUE_3)));
    rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_2), Bytes.toBytes(VALUE_4)));
    cellSetModel.addRow(rowModel);
    Response response = client.put(path, MIMETYPE_PROTOBUF, cellSetModel.createProtobufOutput());
    Thread.yield();

    // make sure the fake row was not actually created
    response = client.get(path, MIMETYPE_PROTOBUF);
    assertEquals(response.getCode(), 404);

    // check that all of the values were created
    checkValuePB(TABLE, ROW_1, COLUMN_1, VALUE_1);
    checkValuePB(TABLE, ROW_1, COLUMN_2, VALUE_2);
    checkValuePB(TABLE, ROW_2, COLUMN_1, VALUE_3);
    checkValuePB(TABLE, ROW_2, COLUMN_2, VALUE_4);

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

From source file:edu.utah.further.i2b2.hook.further.FurtherInterceptionFilter.java

/**
 * Send the i2b2 query request message to the FURTHeR FQE. Must be run after the i2b2
 * processing chain, because it depends on the i2b2 query ID generated by the i2b2
 * server.//from   w  w  w .  ja va2 s  .  c  o m
 * 
 * @param request
 * @param i2b2QueryId
 *            i2b2 query ID, obtained from the i2b2 response
 */
private void spawnFurtherRequest(final HttpServletRequest request, final long i2b2QueryId) {
    if (log.isDebugEnabled()) {
        log.debug("Read i2b2QueryId from request: " + i2b2QueryId);
    }
    try {
        // Need to read create from request.getInputStream() multiple times
        // in this method ==> save a copy in a buffer first
        // inputStream is already at the end of the file.
        final InputStream inputStream = request.getInputStream();
        final byte[] buffer = CoreUtil.readBytesFromStream(inputStream);
        inputStream.close();

        // Decide whether to fork or not
        if (StringUtil.isValidLong(i2b2QueryId) && isProcessRequest(buffer)) {
            // Read the FURTHeR section of the i2b2 request body
            final String requestXml = new String(buffer);
            // Request contains an FQE processing flag, send to FURTHeR
            if (log.isDebugEnabled()) {
                ServletUtil.printRequestHeaders(request);
                ServletUtil.printRequestParameters(request);
                ServletUtil.printRequestAttributes(request);
            }

            // TODO: read query instance id from i2b2 response and pass to the
            // following call
            final QueryContextIdentifier id = furtherServices.i2b2QueryRequest(requestXml, i2b2QueryId);

            // Make available to response through the request, ensures thread safety
            // instead of using instance var
            request.setAttribute(QUERY_ID, id);

            QueryState state = furtherServices.getQueryState(id).getState();

            final StopWatch stopWatch = new StopWatch();

            final int interval = 10;
            int i = 0;
            stopWatch.start();
            // Poll state every sec
            final long maxQueryTimeMillis = furtherServices.getMaxQueryTime() * 1000;
            while (state != QueryState.COMPLETED && state != QueryState.STOPPED && state != QueryState.FAILED
                    && state != QueryState.INVALID && state != null
                    && stopWatch.getTime() < maxQueryTimeMillis) {
                Thread.yield();
                state = furtherServices.getQueryState(id).getState();

                if (log.isDebugEnabled() && ((i % interval) == 0)) {
                    log.debug("QueryState for query " + id.getId() + ": " + state);
                }

                i++;
            }
            stopWatch.stop();
        } else {
            if (log.isDebugEnabled()) {
                log.info("Ignoring unrecognized/irrelvant requestXml");
            }
        }
    } catch (final Throwable throwable) {
        if (log.isDebugEnabled()) {
            log.error("Caught " + throwable + ", ignoring", throwable);
        }
    }
}

From source file:uk.co.real_logic.aeron.tools.ThwackerTool.java

/**
 * Worker Thread Method://w w  w  .  j  a v a  2s. co m
 * Randomly selects a slot out of the subscription array and creates a subscription
 * if there isn't on there already
 */
public void createSubs() {
    final Random rand = SeedableThreadLocalRandom.current();
    int i;
    ThwackingElement sub;
    while (running) {
        if (active) {
            i = rand.nextInt(numberOfSubscriptions);
            sub = subs[i];
            sub.tryAddSub();
        }
        Thread.yield();
    }
    allDone.countDown();
    LOG.fine("CreateSubs all done!");
}

From source file:org.mule.providers.ldap.MuleEmbeddedTestCase.java

public void testDispatchReceiveAddStress() throws Exception {
    final MuleClient client = new MuleClient();

    final int count = 10000;

    Runnable rec = new Runnable() {

        public void run() {

            int current = 0;

            try {

                while (current < count) {
                    UMOMessage result = client.receive("ldap://ldap.in", 15000);

                    assertNotNull(result);
                    assertTrue(result.getPayload() instanceof LDAPResponse);
                    assertEquals(((LDAPResponse) result.getPayload()).getResultCode(), LDAPException.SUCCESS);
                    assertEquals(((LDAPResponse) result.getPayload()).getType(), LDAPMessage.ADD_RESPONSE);
                    logger.debug("got " + current);
                    current++;//from www .j a  v a2s .c om
                }

            } catch (UMOException e) {
                fail(e.toString());

            }

            assertTrue(current == count);

        }

    };

    Thread t = new Thread(rec);
    t.start();

    Thread.yield();

    // we send a message on the endpoint we created, i.e. vm://Single
    for (int i = 0; i < count; i++)
        client.dispatch("ldap://ldap.out", TestHelper.getRandomEntryAddRequest(), null);

    t.join();

}

From source file:com.adito.core.LineInput.java

private void fill() throws IOException {
    // if the mark is in the middle of the buffer
    if (_mark > 0) {
        // moved saved bytes to start of buffer
        int saved = _contents - _mark;
        System.arraycopy(_buf, _mark, _buf, 0, saved);
        _pos -= _mark;/*  w w w.j  a v  a2 s  .c o  m*/
        _avail -= _mark;
        _contents = saved;
        _mark = 0;
    } else if (_mark < 0 && _pos > 0) {
        // move remaining bytes to start of buffer
        int saved = _contents - _pos;
        System.arraycopy(_buf, _pos, _buf, 0, saved);
        _avail -= _pos;
        _contents = saved;
        _pos = 0;
    } else if (_mark == 0 && _pos > 0 && _contents == _buf.length) {
        // Discard the mark as we need the space.
        _mark = -1;
        fill();
        return;
    }

    // Get ready to top up the buffer
    int n = 0;
    _eof = false;

    // Handle byte limited EOF
    if (_byteLimit == 0)
        _eof = true;
    // else loop until something is read.
    else
        while (!_eof && n == 0 && _buf.length > _contents) {
            // try to read as much as will fit.
            int space = _buf.length - _contents;

            n = in.read(_buf, _contents, space);

            if (n <= 0) {
                // If no bytes - we could be NBIO, so we want to avoid
                // a busy loop.
                if (n == 0) {
                    // Yield to give a chance for some bytes to turn up
                    Thread.yield();

                    // Do a byte read as that is blocking
                    int b = in.read();
                    if (b >= 0) {
                        n = 1;
                        _buf[_contents++] = (byte) b;
                    } else
                        _eof = true;
                } else
                    _eof = true;
            } else
                _contents += n;
            _avail = _contents;

            // If we have a byte limit
            if (_byteLimit > 0) {
                // adjust the bytes available
                if (_contents - _pos >= _byteLimit)
                    _avail = _byteLimit + _pos;

                if (n > _byteLimit)
                    _byteLimit = 0;
                else if (n >= 0)
                    _byteLimit -= n;
                else if (n == -1)
                    throw new IOException("Premature EOF");
            }
        }

    // If we have some characters and the last read was a CR and
    // the first char is a LF, skip it
    if (_avail - _pos > 0 && _lastCr && _buf[_pos] == LF) {
        _seenCrLf = true;
        _pos++;
        if (_mark >= 0)
            _mark++;
        _lastCr = false;

        // If the byte limit has just been imposed, dont count
        // LF as content.
        if (_byteLimit >= 0 && _newByteLimit) {
            if (_avail < _contents)
                _avail++;
            else
                _byteLimit++;
        }
        // If we ate all that ws filled, fill some more
        if (_pos == _avail)
            fill();
    }
    _newByteLimit = false;
}

From source file:org.trianacode.taskgraph.service.RunnableTask.java

/**
 * creates the thread to run the unit, or set a flag to re-run the existing thread
 *//*from   w w w.j  av  a2  s.  c  o m*/
public final synchronized void startThread() {
    boolean handled = false;
    wakeups.clear();

    do {
        synchronized (THREAD_LOCK) {
            if (threadstate != UNSTABLE) {
                executionRequested();

                if (threadstate == IN_PROCESS) {
                    runAgain++;
                } else {
                    runAgain = 0;
                    threadstate = UNSTABLE;

                    getProperties().getEngine().execute(this);
                }
                handled = true;
            } else {
                Thread.yield();
            }
        }
    } while (!handled);
}

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

public void testRoundTripIMAPKoreanCharset() throws Exception {

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

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

    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(KOREAN_TEXT, ((OMElement) result).getText());
            }
        }
    } else {
        fail("Did not receive the reply mail");
    }
}

From source file:com.wifiafterconnect.WifiAuthenticator.java

public boolean attemptAuthentication(ParsedHttpInput currentPage, WifiAuthParams authParams) {

    notifyAuthentication(AuthStatus.INPROGRESS);
    CaptivePageHandler.States captiveState = CaptivePageHandler.States.HandleRedirects;
    /* Some portals supply as the first page ip, MAC etc 
     * inside of the form that has to be submitted onLoad.
     * Wandering WiFi is the worst offender.
     *//*from ww  w.j a  v a2 s.  c  o m*/
    while (captiveState != CaptivePageHandler.States.Success
            && captiveState != CaptivePageHandler.States.Failed) {

        debug("Handling pre-auth redirects. parsedPage = " + currentPage);
        // don't want to do meta http-equiv=refresh here as it is used to detect browsers with no JS support
        // and display error requiring it
        if ((currentPage = currentPage.handleAutoRedirects(Constants.MAX_AUTOMATED_REQUESTS, false)) == null) {
            error("Failed to follow the sequence of redirects...");
            notifyAuthentication(AuthStatus.FAIL);
            return false;
        }
        debug("Done handling pre-auth redirects. parsedPage = " + currentPage);

        if (!currentPage.isKnownCaptivePortal()) {
            error("Unknown Captive portal. Aborting.");
            notifyAuthentication(AuthStatus.FAIL);
            return false;
        }

        if (!checkTNCShown(currentPage)) {
            notifyAuthentication(AuthStatus.FAIL);
            return false; // it is the first time that user connected to this SSID , 
            // so we let them go through the proper web authentication.
        }

        debug("Checking for missing inputs at [" + currentPage.getURL() + "]");
        if (authParams == null) {
            authParams = getStoredAuthParams();

            if (currentPage.checkParamsMissing(authParams)) {
                requestUserParams(currentPage);
                // we will have to try authentication directly from user-facing activity
                return false;
            }
        }

        debug("Attempting authentication at [" + currentPage.getURL() + "]");
        ParsedHttpInput nextPage = currentPage.authenticateCaptivePortal(authParams);
        captiveState = (nextPage == null) ? CaptivePageHandler.States.Failed
                : currentPage.getCaptivePortalState();
        currentPage = nextPage;
    }

    AuthStatus status = AuthStatus.valueOf(captiveState);

    if (status.isSuccess()) {
        debug("Re-checking connection ...");
        URLRedirectChecker checker = new URLRedirectChecker(this);
        status = AuthStatus.valueOf(checker.checkHttpConnection(AuthorizationType.None));
        if (status.isSuccess()) {
            WifiAuthDatabase wifiDb = getDb();
            debug("Saving Auth Params. db = [" + wifiDb + "]");
            if (wifiDb != null)
                wifiDb.storeAuthParams(authHost, authParams);
            if (getContext() != null) {
                cancelWatchdogNotification();
                try {
                    //Toast.makeText(context, context.getText(R.string.success_notification) + " " + authHost, Toast.LENGTH_SHORT).show();
                } catch (Throwable e) {
                    // don't care
                }
                // do we need this so that Toast would actually display ?
                Thread.yield();
            }
        }
    }

    notifyAuthentication(status);
    return status.isSuccess();
}

From source file:uk.co.real_logic.aeron.tools.ThwackerTool.java

/**
 * Worker Thread Method://  w ww.j av  a  2s  .com
 * Randomly selects a subscription and deletes it if no other threads are using that specific subscription
 */

public void deleteSubs() {
    final Random rand = SeedableThreadLocalRandom.current();
    int i;
    ThwackingElement sub;
    while (running) {
        if (active) {
            i = rand.nextInt(numberOfSubscriptions);
            sub = subs[i];
            sub.tryRemoveSub();
        }
        try {
            Thread.sleep(1);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
        Thread.yield();
    }
    allDone.countDown();
    LOG.fine("DeleteSubs all done!");
}