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.hadoop.hbase.rest.RowResourceBase.java

protected static Response checkAndDeleteJson(String url, String table, String row, String column,
        String valueToCheck, HashMap<String, String> cellsToDelete) throws IOException, JAXBException {
    RowModel rowModel = new RowModel(row);

    if (cellsToDelete != null) {
        for (Map.Entry<String, String> entry : cellsToDelete.entrySet()) {
            rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
        }//from  w ww  . j  a  va  2s.co m
    }
    // Add this at the end
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(valueToCheck)));
    CellSetModel cellSetModel = new CellSetModel();
    cellSetModel.addRow(rowModel);
    String jsonString = jsonMapper.writeValueAsString(cellSetModel);
    Response response = client.put(url, Constants.MIMETYPE_JSON, Bytes.toBytes(jsonString));
    Thread.yield();
    return response;
}

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

/**
 * Worker thread method that will iterate over the list of subscriptions and call poll()
 *//*from w w  w  . j ava  2 s  .com*/

public void receiveOnSubs() {
    while (running) {
        /* Run through each sub slot sequentially */
        for (final ThwackingElement s : subs) {
            s.tryGetMessages();
        }
        Thread.yield();
        /* Every iteration calls poll() on the control subscription */
        ctrlSub.tryGetMessages();
    }
    allDone.countDown();
    LOG.fine("RecSubs all done!");
}

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

@Test
public void testMultiCellGetPutXML() throws IOException, JAXBException {
    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 w  w w  . j  a v a  2  s  .c  om
    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);
    StringWriter writer = new StringWriter();
    xmlMarshaller.marshal(cellSetModel, writer);
    Response response = client.put(path, Constants.MIMETYPE_XML, Bytes.toBytes(writer.toString()));
    Thread.yield();

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

    // check that all of the values were created
    checkValueXML(TABLE, ROW_1, COLUMN_1, VALUE_1);
    checkValueXML(TABLE, ROW_1, COLUMN_2, VALUE_2);
    checkValueXML(TABLE, ROW_2, COLUMN_1, VALUE_3);
    checkValueXML(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:org.opencms.staticexport.CmsAfterPublishStaticExportHandler.java

/**
 * Exports all non template resources found in a list of published resources.<p>
 * // w w w. j av  a2s  .  c o m
 * @param cms the current cms object
 * @param publishedResources the list of published resources
 * @param report an I_CmsReport instance to print output message, or null to write messages to the log file
 * 
 * @return true if some template resources were found while looping the list of published resources
 * 
 * @throws CmsException in case of errors accessing the VFS
 * @throws IOException in case of errors writing to the export output stream
 * @throws ServletException in case of errors accessing the servlet 
 */
protected boolean exportNonTemplateResources(CmsObject cms, List<CmsPublishedResource> publishedResources,
        I_CmsReport report) throws CmsException, IOException, ServletException {

    report.println(Messages.get().container(Messages.RPT_STATICEXPORT_NONTEMPLATE_RESOURCES_BEGIN_0),
            I_CmsReport.FORMAT_HEADLINE);

    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_EXPORTING_NON_TEMPLATE_1,
                new Integer(publishedResources.size())));
    }

    CmsStaticExportManager manager = OpenCms.getStaticExportManager();
    List<CmsStaticExportData> resourcesToExport = new ArrayList<CmsStaticExportData>();
    boolean templatesFound = readNonTemplateResourcesToExport(cms, publishedResources, resourcesToExport);

    int count = 1;
    int size = resourcesToExport.size();
    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_NUM_EXPORT_1, new Integer(size)));
    }
    // now do the export
    Iterator<CmsStaticExportData> i = resourcesToExport.iterator();
    while (i.hasNext()) {
        CmsStaticExportData exportData = i.next();
        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_EXPORT_FILE_2, exportData.getVfsName(),
                    exportData.getRfsName()));
        }

        report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SUCCESSION_2,
                new Integer(count++), new Integer(size)), I_CmsReport.FORMAT_NOTE);
        report.print(Messages.get().container(Messages.RPT_EXPORTING_0), I_CmsReport.FORMAT_NOTE);
        report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ARGUMENT_1,
                exportData.getVfsName()));
        report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
        int status = manager.export(null, null, cms, exportData);
        if (status == HttpServletResponse.SC_OK) {
            report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                    I_CmsReport.FORMAT_OK);
        } else {
            report.println(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_IGNORED_0),
                    I_CmsReport.FORMAT_NOTE);
        }

        if (LOG.isInfoEnabled()) {
            Object[] arguments = new Object[] { exportData.getVfsName(), exportData.getRfsName(),
                    new Integer(status) };
            LOG.info(Messages.get().getBundle().key(Messages.LOG_EXPORT_FILE_STATUS_3, arguments));
        }
        //don't lock up the CPU exclusively - allow other Threads to run as well 
        Thread.yield();
    }

    resourcesToExport = null;

    report.println(Messages.get().container(Messages.RPT_STATICEXPORT_NONTEMPLATE_RESOURCES_END_0),
            I_CmsReport.FORMAT_HEADLINE);

    return templatesFound;
}

From source file:org.apache.hadoop.hive.metastore.AggregateStatsCache.java

/**
 * Cleans the expired nodes or removes LRU nodes of the cache,
 * until the cache size reduces to cleanUntil% full.
 *//*from   w w w  .  j a  va 2  s  .  co  m*/
private void spawnCleaner() {
    // This spawns a separate thread to walk through the cache and removes expired nodes.
    // Only one cleaner thread should be running at any point.
    synchronized (this) {
        if (isCleaning) {
            return;
        }
        isCleaning = true;
    }
    Thread cleaner = new Thread("AggregateStatsCache-CleanerThread") {
        @Override
        public void run() {
            numRemovedTTL = 0;
            numRemovedLRU = 0;
            long cleanerStartTime = System.currentTimeMillis();
            LOG.info("AggregateStatsCache is " + getFullPercent() + "% full, with " + getCurrentNodes()
                    + " nodes; starting cleaner thread");
            try {
                Iterator<Map.Entry<Key, AggrColStatsList>> mapIterator = cacheStore.entrySet().iterator();
                while (mapIterator.hasNext()) {
                    Map.Entry<Key, AggrColStatsList> pair = (Map.Entry<Key, AggrColStatsList>) mapIterator
                            .next();
                    AggrColStats node;
                    AggrColStatsList candidateList = (AggrColStatsList) pair.getValue();
                    List<AggrColStats> nodes = candidateList.nodes;
                    if (nodes.size() == 0) {
                        mapIterator.remove();
                        continue;
                    }
                    boolean isLocked = false;
                    try {
                        isLocked = candidateList.writeLock.tryLock(maxWriterWaitTime, TimeUnit.MILLISECONDS);
                        if (isLocked) {
                            for (Iterator<AggrColStats> listIterator = nodes.iterator(); listIterator
                                    .hasNext();) {
                                node = listIterator.next();
                                // Remove the node if it has expired
                                if (isExpired(node)) {
                                    listIterator.remove();
                                    numRemovedTTL++;
                                    currentNodes.getAndDecrement();
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        LOG.debug(e);
                    } finally {
                        if (isLocked) {
                            candidateList.writeLock.unlock();
                        }
                    }
                    // We want to make sure this runs at a low priority in the background
                    Thread.yield();
                }
                // If the expired nodes did not result in cache being cleanUntil% in size,
                // start removing LRU nodes
                while (getCurrentNodes() / maxCacheNodes > cleanUntil) {
                    evictOneNode();
                }
            } finally {
                isCleaning = false;
                LOG.info("Stopping cleaner thread; AggregateStatsCache is now " + getFullPercent()
                        + "% full, with " + getCurrentNodes() + " nodes");
                LOG.info("Number of expired nodes removed: " + numRemovedTTL);
                LOG.info("Number of LRU nodes removed: " + numRemovedLRU);
                LOG.info("Cleaner ran for: " + (System.currentTimeMillis() - cleanerStartTime) + "ms");
            }
        }
    };
    cleaner.setPriority(Thread.MIN_PRIORITY);
    cleaner.setDaemon(true);
    cleaner.start();
}

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

public void stop() throws InterruptedException {
    synchronized (this) {
        // Signal that we are stopping
        _running = false;/*from w ww. j ava 2s. c  o m*/

        // Close the listener socket.
        if (log.isDebugEnabled())
            log.debug("closing " + _listen);
        try {
            if (_listen != null)
                _listen.close();
            _listen = null;
        } catch (IOException e) {
            log.warn(LogSupport.EXCEPTION, e);
        }

        // Do we have an acceptor thread (running or not)
        Thread.yield();
        for (int a = 0; _acceptor != null && a < _acceptor.length; a++) {
            Acceptor acc = _acceptor[a];
            if (acc != null)
                acc.interrupt();
        }
        Thread.sleep(100);

        for (int a = 0; _acceptor != null && a < _acceptor.length; a++) {
            Acceptor acc = _acceptor[a];

            if (acc != null) {
                acc.forceStop();
                _acceptor[a] = null;
            }
        }
    }

    // Stop the thread pool
    try {
        super.stop();
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    } finally {
        synchronized (this) {
            _acceptor = null;
        }
    }
}

From source file:com.apporiented.hermesftp.client.FtpTestClient.java

private void executeSend(TextSender l) {
    Thread t = new Thread(l);
    t.start();
    while (t.isAlive()) {
        Thread.yield();
    }
}

From source file:org.mule.transport.ldap.functional.MuleEmbeddedTestCase.java

public synchronized void testDispatchReceiveSearchDeleted() throws Exception {
    final MuleClient client = new MuleClient(muleContext);

    final int addCount = 4;
    LDAPAddRequest last = null;/*from   www  .j  ava  2 s  . co  m*/

    for (int i = 0; i < addCount; i++) {
        client.dispatch("ldap://ldap.out", last = TestHelper.getRandomEntryAddRequest(), null);
    }

    Thread.yield();
    Thread.sleep(10000);

    client.dispatch("ldap://ldap.out", new LDAPDeleteRequest(last.getEntry().getDN(), null), null);

    Thread.yield();
    Thread.sleep(10000);

    // we send a message on the endpoint we created, i.e. vm://Single
    client.dispatch("ldap://ldap.out/cn.payload", last.getEntry().getDN(), null);

    Thread.yield();
    Thread.sleep(10000);

    MuleMessage result = null;
    MuleMessage lastResult = null;

    int count = 0;

    // addCount AddResponses, 1x Search Result, 1 delete response
    final int expected = addCount + 1 + 1;

    while (true) {
        result = client.request("ldap://ldap.in", 15000);

        if (result == null) {
            break;
        }

        logger.debug(LDAPUtils.dumpLDAPMessage(result.getPayload()));

        lastResult = result;
        count++;
    }

    assertTrue("Count (" + count + ") != expected (" + expected + ")", count == expected); // fails because of list returnded or
    // processing time to short?
    assertNull(result);
    assertNotNull(lastResult);
    assertTrue("instanceof " + lastResult.getPayload().getClass() + " instead of LDAPResponse",
            lastResult.getPayload() instanceof LDAPResponse);

    // TODO order is not predictable
    // assertTrue(
    // "Check type: "
    // + ((LDAPResponse) lastResult.getPayload()).getType()
    // + " should be " + LDAPMessage.SEARCH_RESULT,
    // ((LDAPResponse) lastResult.getPayload()).getType() ==
    // LDAPMessage.SEARCH_RESULT);

    // is 2xaddresponse, 1 searchresult, 1 addresponse, 1 delresponse, 1
    // addresponse

    try {
        DSManager.getInstance().stop();
    } catch (final Exception e) {

    }

}

From source file:fs.MainWindow.java

public void ExecuteFeatureSelection(int selector) throws IOException {
    String penalization_type = (String) jCB_PenalizationSE.getSelectedItem();
    float alpha = ((Double) jS_AlphaSE.getValue()).floatValue();
    float q_entropy = ((Double) jS_QEntropySE.getValue()).floatValue();
    float beta = ((float) jSliderBetaSE.getValue() / 100);

    //if selected criterion function is CoD, q_entropy = 0
    if (jCB_CriterionFunctionSE.getSelectedIndex() == 1) {
        q_entropy = 0;/*  www . ja  va  2  s.  c om*/
    } //CoD

    if (q_entropy < 0 || alpha < 0) {
        //entrada de dados invalida.
        JOptionPane.showMessageDialog(this,
                "Error on parameter value:The" + " values of q-entropy and Alpha must be positives.",
                "Application Error", JOptionPane.ERROR_MESSAGE);
        return;
    }

    jTA_SaidaSE.setText("");
    jTA_SelectedFeaturesSE.setText("");

    // n = quantidade de valores assumidos pelas caracteristicas.
    int n = Main.maximumValue(Md, 0, lines - 1, 0, columns - 2) + 1;

    //c = numero de rotulos possiveis para as classes.
    int c = Main.maximumValue(Md, 0, lines - 1, columns - 1, columns - 1) + 1;

    jProgressBarSE.setValue(5);
    Thread.yield();

    char[][] strainingset = MathRoutines.float2char(Md);
    char[][] stestset = null;

    if (!jTF_InputTestSE.getText().equals("")) {
        stestset = IOFile.readMatrix(jTF_InputTestSE.getText(), delimiter);
    } else {
        stestset = MathRoutines.float2char(Md);
    }

    int resultsetsize = 1;
    try {
        //vetor com os resultados da selecao de caracteristica.
        resultsetsize = (Integer) jS_MaxResultListSE.getValue();
        if (resultsetsize < 1) {
            Thread.yield();
            JOptionPane
                    .showMessageDialog(this,
                            "Error on parameter value:" + " The Size of the Result List must be a integer value"
                                    + " greater or equal to 1.",
                            "Application Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    } catch (NumberFormatException error) {
        Thread.yield();
        JOptionPane.showMessageDialog(
                this, "Error on parameter value: The"
                        + " Size of the Result List must be a integer value greater" + " or equal to 1.",
                "Application Error", JOptionPane.ERROR_MESSAGE);
        return;
    }

    /* SELETOR DE CARACTERISTICAS PARA O TREINAMENTO. */
    FS fs = new FS(strainingset, n, c, penalization_type, alpha, beta, q_entropy, resultsetsize);

    jProgressBarSE.setValue(10);
    Thread.yield();

    int maxfeatures = (Integer) jS_MaxSetSizeSE.getValue();
    if (maxfeatures <= 0) {
        JOptionPane.showMessageDialog(this, "Error on parameter value: The"
                + " Maximum Set Size be a integer value greater" + " or equal to 1.", "Application Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    if (selector == 1) {
        fs.runSFS(false, maxfeatures);
        jProgressBarSE.setValue(90);
        Thread.yield();
    } else if (selector == 3) {
        fs.runSFFS(maxfeatures, -1, null);
        jProgressBarSE.setValue(90);
        Thread.yield();
    } else if (selector == 2) {
        fs.runSFS(true, maxfeatures); /* a call to SFS is made in order to get the
                                      //ideal dimension to run the exhaustive search;*/
        int itmax = fs.itmax;
        if (itmax < maxfeatures) {
            itmax = maxfeatures;
        }
        /*calculating the estimated time to be completed in rea
        computer of 2 GHz*/
        int combinations = 0;
        for (int i = 1; i <= itmax; i++) {
            combinations += MathRoutines.numberCombinations(columns - 1, i);
        }
        double estimatedTime = (0.0062 + 3.2334e-7 * strainingset.length) * combinations
                * Math.log(combinations) / Math.log(2);
        int answer = JOptionPane.showConfirmDialog(null,
                "Estimated " + "time to finish: " + estimatedTime + " s.\n Do you want to" + " continue?",
                "Exhaustive Search", JOptionPane.YES_NO_OPTION);
        if (answer == 1) {
            jProgressBarSE.setValue(0);
            return;
        }
        //System.out.println("Estimated time to finish: "+estimatedTime+" s");
        float new_itmax = itmax;
        FS fsPrev = new FS(strainingset, n, c, penalization_type, alpha, beta, q_entropy, resultsetsize);
        for (int i = 1; i <= itmax; i++) {
            System.out.println("Iteration " + i);
            fs = new FS(strainingset, n, c, penalization_type, alpha, beta, q_entropy, resultsetsize);
            fs.itmax = i;
            fs.runExhaustive(0, 0, fs.I);
            //if (fs.hGlobal == 0) {
            //    break;
            //}
            if (fs.hGlobal < fsPrev.hGlobal) {
                fsPrev = fs;
            } else {
                fs = fsPrev;
                break;
            }
            float new_i = i;
            float pb = (new_i / new_itmax);
            pb = (pb * 80.0f);
            jProgressBarSE.setValue(10 + (int) pb);
            Thread.yield();
        }
    }

    /*
    jTA_SelectedFeaturesSE.setText("1st Global Criterion Function Value: " + fs.hGlobal);
    jTA_SelectedFeaturesSE.append("\nSelected Features: ");
    for (int i = 0; i < fs.I.size(); i++) {
    jTA_SelectedFeaturesSE.append(fs.I.elementAt(i) + " ");
    }
     * substituido pelo codigo abaixo para exibir uma lista de resultados
     * de tamanho escolhido pelo usuario.
     */
    for (int i = 0; i < fs.resultlist.size(); i++) {
        float fsvalue = ((Float) fs.resultlist.get(i).get(0));
        if (i == 0) {
            jTA_SelectedFeaturesSE.setText((i + 1) + "st Global Criterion" + " Function Value: " + fsvalue);
        } else if (i == 1) {
            jTA_SelectedFeaturesSE
                    .append("\n\n" + (i + 1) + "nd Global" + " Criterion Function Value: " + fsvalue);
        } else if (i == 2) {
            jTA_SelectedFeaturesSE
                    .append("\n\n" + (i + 1) + "rd Global" + " Criterion Function Value: " + fsvalue);
        } else {
            jTA_SelectedFeaturesSE
                    .append("\n\n" + (i + 1) + "th Global" + " Criterion Function Value: " + fsvalue);
        }
        jTA_SelectedFeaturesSE.append("\nSelected Features: ");
        Vector features = (Vector) fs.resultlist.get(i).get(1);
        for (int j = 0; j < features.size(); j++) {
            jTA_SelectedFeaturesSE.append((Integer) features.get(j) + " ");
        }
    }

    // CLASSIFICADOR.
    Classifier clas = new Classifier();
    clas.classifierTable(strainingset, fs.I, n, c);
    for (int i = 0; i < clas.table.size(); i++) {
        double[] tableLine = (double[]) clas.table.elementAt(i);
        double instance = (Double) clas.instances.elementAt(i);
        System.out.print(instance + " ");
        for (int j = 0; j < c; j++) {
            System.out.print((int) tableLine[j] + " ");
        }
        System.out.println();
    }
    jProgressBarSE.setValue(95);
    Thread.yield();
    double[] instances = clas.classifyTestSamples(stestset, fs.I, n, c);
    jTA_SaidaSE.setText("Correct Labels  -  Classified Labels - "
            + "Classification Instances\n(Considering the first selected" + " features)\n");
    double hits = 0;
    for (int i = 0; i < clas.labels.length; i++) {
        int correct_label = (int) stestset[i][columns - 1];
        int classified_label = (int) clas.labels[i];
        jTA_SaidaSE.append("\n" + correct_label + "  -  " + classified_label + "  -  " + instances[i]);
        if (correct_label == classified_label) {
            hits++;
        }
        Thread.yield();
    }
    double hit_rate = hits / clas.labels.length;
    jTA_SaidaSE.append("\nrate of hits = " + hit_rate);
    jProgressBarSE.setValue(100);
    Thread.yield();
}

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

protected static Response checkAndDeleteValuePB(String url, String table, String row, String column,
        String valueToCheck, HashMap<String, String> cellsToDelete) throws IOException {
    RowModel rowModel = new RowModel(row);

    if (cellsToDelete != null) {
        for (Map.Entry<String, String> entry : cellsToDelete.entrySet()) {
            rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
        }/*from  w w  w.  j  a v  a 2s. c  o  m*/
    }
    // Add this at the end
    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;
}