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:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public boolean setUpNetwork(String sIniFile) {
    boolean bRet = false;
    int lcv = 0;//from  ww w.j a  v  a  2 s  . c  om
    int lcv2 = 0;
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wc = new WifiConfiguration();
    DoCommand tmpdc = new DoCommand(getApplication());

    String ssid = tmpdc.GetIniData("Network Settings", "SSID", sIniFile);
    String auth = tmpdc.GetIniData("Network Settings", "AUTH", sIniFile);
    String encr = tmpdc.GetIniData("Network Settings", "ENCR", sIniFile);
    String key = tmpdc.GetIniData("Network Settings", "KEY", sIniFile);
    String eap = tmpdc.GetIniData("Network Settings", "EAP", sIniFile);
    String adhoc = tmpdc.GetIniData("Network Settings", "ADHOC", sIniFile);

    Toast.makeText(getApplication().getApplicationContext(), "Starting and configuring network",
            Toast.LENGTH_LONG).show();
    /*
            ContentResolver cr = getContentResolver();
            int nRet;
            try {
    nRet = Settings.System.getInt(cr, Settings.System.WIFI_USE_STATIC_IP);
    String foo2 = "" + nRet;
            } catch (SettingNotFoundException e1) {
    e1.printStackTrace();
            }
    */
    /*
            wc.SSID = "\"Mozilla-Build\"";
            wc.preSharedKey  = "\"MozillaBuildQA500\"";
            wc.hiddenSSID = true;
            wc.status = WifiConfiguration.Status.ENABLED;
            wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    */
    wc.SSID = "\"" + ssid + "\"";
    //        wc.SSID = "\"Mozilla-G\"";
    //        wc.SSID = "\"Mozilla\"";

    if (auth.contentEquals("wpa2")) {
        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wc.preSharedKey = null;
    }

    if (encr.contentEquals("aes")) {
        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    }

    if (eap.contentEquals("peap")) {
        wc.eap.setValue("PEAP");
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
    }

    wc.status = WifiConfiguration.Status.ENABLED;

    if (!wifi.isWifiEnabled())
        wifi.setWifiEnabled(true);

    while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
        Thread.yield();
        if (++lcv > 10000)
            return (bRet);
    }

    wl = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL, "SUTAgent");
    if (wl != null)
        wl.acquire();

    WifiConfiguration foo = null;
    int nNetworkID = -1;

    List<WifiConfiguration> connsLst = wifi.getConfiguredNetworks();
    int nConns = connsLst.size();
    for (int i = 0; i < nConns; i++) {

        foo = connsLst.get(i);
        if (foo.SSID.equalsIgnoreCase(wc.SSID)) {
            nNetworkID = foo.networkId;
            wc.networkId = foo.networkId;
            break;
        }
    }

    int res;

    if (nNetworkID != -1) {
        res = wifi.updateNetwork(wc);
    } else {
        res = wifi.addNetwork(wc);
    }

    Log.d("WifiPreference", "add Network returned " + res);

    boolean b = wifi.enableNetwork(res, true);
    Log.d("WifiPreference", "enableNetwork returned " + b);

    wifi.saveConfiguration();

    WifiInfo wi = wifi.getConnectionInfo();
    SupplicantState ss = wi.getSupplicantState();

    lcv = 0;
    lcv2 = 0;

    while (ss.compareTo(SupplicantState.COMPLETED) != 0) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (wi != null)
            wi = null;
        if (ss != null)
            ss = null;
        wi = wifi.getConnectionInfo();
        ss = wi.getSupplicantState();
        if (++lcv > 60) {
            if (++lcv2 > 5) {
                Toast.makeText(getApplication().getApplicationContext(),
                        "Unable to start and configure network", Toast.LENGTH_LONG).show();
                return (bRet);
            } else {
                Toast.makeText(getApplication().getApplicationContext(), "Resetting wifi interface",
                        Toast.LENGTH_LONG).show();
                if (wl != null)
                    wl.release();
                wifi.setWifiEnabled(false);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
                    Thread.yield();
                }

                wifi.setWifiEnabled(true);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
                    Thread.yield();
                }
                b = wifi.enableNetwork(res, true);
                Log.d("WifiPreference", "enableNetwork returned " + b);
                if (wl != null)
                    wl.acquire();
                lcv = 0;
            }
        }
    }

    lcv = 0;
    while (getLocalIpAddress() == null) {
        if (++lcv > 10000)
            return (bRet);
    }

    Toast.makeText(getApplication().getApplicationContext(), "Network started and configured",
            Toast.LENGTH_LONG).show();
    bRet = true;

    return (bRet);
}

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

@Test
public void testMultiCellGetJson() 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);// w  w w.  ja  va2  s  .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);
    String jsonString = jsonMapper.writeValueAsString(cellSetModel);

    Response response = client.put(path, Constants.MIMETYPE_JSON, Bytes.toBytes(jsonString));
    Thread.yield();

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

    // check that all of the values were created
    checkValueJSON(TABLE, ROW_1, COLUMN_1, VALUE_1);
    checkValueJSON(TABLE, ROW_1, COLUMN_2, VALUE_2);
    checkValueJSON(TABLE, ROW_2, COLUMN_1, VALUE_3);
    checkValueJSON(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.sonatype.nexus.test.booter.Jetty8NexusBooter.java

/**
 * Cleans the references to IT-realm, making it garbage collectable (naturally, this can be only "best effort").
 *///from  w ww. j  ava  2s .c  o  m
protected void clean() {
    if (nexusClassloader != null) {
        try {
            world.disposeRealm(nexusClassloader.getId());
        } catch (NoSuchRealmException e) {
            // huh?
        }
    }

    // drop references
    this.jetty8 = null;
    this.nexusClassloader = null;

    // give some relief for other (like JVM internal) threads
    Thread.yield();

    // force GC, may help
    System.gc();
}

From source file:org.apache.jackrabbit.core.query.lucene.JahiaSearchIndex.java

void updateNodes(Iterator<NodeId> remove, Iterator<NodeState> add, boolean waitForIndexSwitch)
        throws RepositoryException, IOException {

    if (waitForIndexSwitch) {
        waitForIndexSwitch();//w w  w . j a  v a 2 s .  c  o m

        if (ignoredTypes != null && add.hasNext()) {
            List<NodeState> l = null;
            while (add.hasNext()) {
                NodeState state = add.next();
                if (state != null && !ignoredTypes.contains(state.getNodeTypeName())) {
                    if (l == null) {
                        l = new LinkedList<NodeState>();
                    }
                    l.add(state);
                }
            }
            add = l != null ? l.iterator() : Collections.<NodeState>emptyIterator();
        }
        if (newIndex != null) {
            newIndex.addDelayedUpdated(remove, add);
        }
    }

    if (isVersionIndex()) {
        super.updateNodes(remove, add);
        return;
    }

    final List<NodeState> addList = new ArrayList<NodeState>();
    final List<NodeId> removeList = new ArrayList<NodeId>();
    final Set<NodeId> removedIds = new HashSet<NodeId>();
    final Set<NodeId> addedIds = new HashSet<NodeId>();
    final List<NodeId> aclChangedList = new ArrayList<NodeId>();
    final Set<NodeId> topIdsRecursedForAcl = new HashSet<NodeId>();

    boolean hasAclOrAce = false;
    while (add.hasNext()) {
        final NodeState state = add.next();
        if (state != null) {
            addedIds.add(state.getNodeId());
            addList.add(state);

            if (!hasAclOrAce
                    && (JNT_ACL.equals(state.getNodeTypeName()) || JNT_ACE.equals(state.getNodeTypeName()))) {
                hasAclOrAce = true;
            }
        }
    }
    while (remove.hasNext()) {
        NodeId nodeId = remove.next();
        removedIds.add(nodeId);
        removeList.add(nodeId);
    }

    boolean debugEnabled = log.isDebugEnabled();

    if (isAddAclUuidInIndex() && hasAclOrAce) {
        final ItemStateManager itemStateManager = getContext().getItemStateManager();
        for (final NodeState node : new ArrayList<NodeState>(addList)) {
            try {
                // if an acl node is added, removed or j:inherit property is changed we need to add/modify ACL_UUID field
                // into parent's and all affected subnodes' index documents
                Event event = null;
                if (add instanceof JahiaSearchManager.NodeStateIterator) {
                    event = ((JahiaSearchManager.NodeStateIterator) add).getEvent(node.getNodeId());
                    // skip adding subnodes if just a property changed and its not j:inherit
                    if (event != null && event.getType() != Event.NODE_ADDED
                            && event.getType() != Event.NODE_REMOVED) {
                        if (!(JNT_ACL.equals(node.getNodeTypeName())
                                && event.getPath().endsWith("/j:inherit"))) {
                            continue;
                        }
                    }
                }

                if (JNT_ACL.equals(node.getNodeTypeName())) {
                    NodeState nodeParent = (NodeState) itemStateManager.getItemState(node.getParentId());
                    addIdToBeIndexed(nodeParent.getNodeId(), addedIds, removedIds, addList, removeList);
                    if (!topIdsRecursedForAcl.contains(nodeParent.getNodeId())
                            && !aclChangedList.contains(nodeParent.getNodeId())) {
                        long startTime = debugEnabled ? System.currentTimeMillis() : 0;

                        recurseTreeForAclIdSetting(nodeParent, addedIds, removedIds, aclChangedList,
                                itemStateManager);
                        topIdsRecursedForAcl.add(node.getParentId());

                        if (debugEnabled) {
                            log.debug(
                                    "ACL updated {}. Recursed down the JCR tree to update the index in {} ms.",
                                    event != null ? event.getPath() : nodeParent.getId(),
                                    System.currentTimeMillis() - startTime);
                        }
                    }
                }
                // if an ace is modified, we need to reindex all its subnodes only if we can use the optimized ACE
                if (JNT_ACE.equals(node.getNodeTypeName())) {
                    NodeState acl = (NodeState) itemStateManager.getItemState(node.getParentId());
                    NodeState nodeParent = (NodeState) itemStateManager.getItemState(acl.getParentId());
                    if (canUseOptimizedACEIndexation(nodeParent)) {
                        addIdToBeIndexed(nodeParent.getNodeId(), addedIds, removedIds, addList, removeList);
                        if (!topIdsRecursedForAcl.contains(nodeParent.getNodeId())
                                && !aclChangedList.contains(nodeParent.getNodeId())) {
                            long startTime = debugEnabled ? System.currentTimeMillis() : 0;

                            recurseTreeForAclIdSetting(nodeParent, addedIds, removedIds, aclChangedList,
                                    itemStateManager);
                            topIdsRecursedForAcl.add(node.getParentId());

                            if (debugEnabled) {
                                log.debug(
                                        "ACE entry updated: {}. Recursed down the JCR tree to update the index in {} ms.",
                                        event != null ? event.getPath() : nodeParent.getId(),
                                        System.currentTimeMillis() - startTime);
                            }
                        }
                    }
                }
            } catch (ItemStateException | RepositoryException e) {
                log.warn(
                        "ACL_UUID field in documents may not be updated, so access rights check in search may not work correctly",
                        e);
            }
        }
    }

    long timer = System.currentTimeMillis();

    try {
        super.updateNodes(removeList.iterator(), addList.iterator());
    } catch (AlreadyClosedException e) {
        if (!switching) {
            throw e;
        }
        // If switching index, updates will be handled in delayed updates
    }

    if (debugEnabled) {
        log.debug("Re-indexed nodes in {} ms: {} removed, {} added",
                new Object[] { (System.currentTimeMillis() - timer), removeList.size(), addList.size() });
    }

    if (!aclChangedList.isEmpty()) {
        int aclSubListStart = 0;
        int aclSubListEnd = Math.min(aclChangedList.size(), batchSize);
        while (aclSubListStart < aclChangedList.size()) {
            if (aclSubListStart > 0) {
                Thread.yield();
            }
            List<NodeState> aclAddList = new ArrayList<NodeState>();
            List<NodeId> aclRemoveList = new ArrayList<NodeId>();
            for (final NodeId node : aclChangedList.subList(aclSubListStart, aclSubListEnd)) {
                try {
                    addIdToBeIndexed(node, addedIds, removedIds, aclAddList, aclRemoveList);
                } catch (ItemStateException e) {
                    log.warn("ACL_UUID field in document for nodeId '" + node.toString()
                            + "' may not be updated, so access rights check in search may not work correctly",
                            e);
                }
            }

            try {
                super.updateNodes(aclRemoveList.iterator(), aclAddList.iterator());
            } catch (AlreadyClosedException e) {
                if (!switching) {
                    throw e;
                }
                // If switching index, updates will be handled in delayed updates
            }

            aclSubListStart += batchSize;
            aclSubListEnd = Math.min(aclChangedList.size(), aclSubListEnd + batchSize);
        }
        if (debugEnabled) {
            log.debug("Re-indexed {} nodes after ACL change in {} ms",
                    new Object[] { aclChangedList.size(), (System.currentTimeMillis() - timer) });
        }
    }
}

From source file:org.voltdb.client.Distributer.java

void drain() throws NoConnectionsException {
    boolean more;
    do {/*  w  ww.  j  a v  a 2 s  .co m*/
        more = false;
        synchronized (this) {
            for (NodeConnection cxn : m_connections) {
                synchronized (cxn.m_callbacks) {
                    more = more || cxn.m_callbacks.size() > 0;
                }
            }
        }
        Thread.yield();
    } while (more);

    synchronized (this) {
        for (NodeConnection cxn : m_connections) {
            assert (cxn.m_callbacks.size() == 0);
        }
    }
}

From source file:info.magnolia.cms.core.DefaultContent.java

@Override
public Lock lock(boolean isDeep, boolean isSessionScoped, long yieldFor)
        throws LockException, RepositoryException {
    long finalTime = System.currentTimeMillis() + yieldFor;
    LockException lockException = null;// w ww. ja  va  2 s .c  o m
    while (System.currentTimeMillis() <= finalTime) {
        try {
            return this.node.lock(isDeep, isSessionScoped);
        } catch (LockException e) {
            // its not an exception yet, still got time
            lockException = e;
        }
        Thread.yield();
    }
    // could not get lock
    throw lockException;
}

From source file:org.apache.hadoop.hbase.rest.TestRowResource.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  av  a  2  s . c  o m
    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();
    marshaller.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:net.nightwhistler.pageturner.fragment.ReadingFragment.java

/**
 * Splits the text to be spoken into chunks and streams
 * them to disk. This method should NOT be called on the
 * UI thread!/*w w  w.j a v  a2s  .  co  m*/
 */
private void doStreamTTSToDisk() {

    Option<Spanned> text = bookView.getStrategy().getText();

    if (isEmpty(text) || !ttsIsRunning()) {
        return;
    }

    String textToSpeak = text.map(c -> c.toString().substring(bookView.getStartOfCurrentPage())).getOrElse("");

    List<String> parts = TextUtil.splitOnPunctuation(textToSpeak);

    int offset = bookView.getStartOfCurrentPage();

    try {

        Option<File> ttsFolderOption = config.getTTSFolder();

        if (isEmpty(ttsFolderOption)) {
            throw new TTSFailedException();
        }

        File ttsFolder = ttsFolderOption.unsafeGet();

        for (int i = 0; i < parts.size() && ttsIsRunning(); i++) {

            LOG.debug("Streaming part " + i + " to disk.");

            String part = parts.get(i);

            boolean lastPart = i == parts.size() - 1;

            //Utterance ID doubles as the filename
            String pageName = "";

            try {
                File pageFile = new File(ttsFolder,
                        "tts_" + UUID.randomUUID().getLeastSignificantBits() + ".wav");
                pageName = pageFile.getAbsolutePath();
                pageFile.createNewFile();
            } catch (IOException io) {
                String message = "Can't write to file \n" + pageName + " because of error\n" + io.getMessage();
                LOG.error(message);
                showTTSFailed(message);
            }

            streamPartToDisk(pageName, part, offset, textToSpeak.length(), lastPart);

            offset += part.length() + 1;

            Thread.yield();
        }
    } catch (TTSFailedException e) {
        //Just stop streaming
    }
}

From source file:de.innovationgate.wgpublisher.lucene.LuceneManager.java

public void destroy() {
    // destroy timer task
    if (_timer != null) {
        _timer.cancel();/*from w  w w. j av a  2 s .co m*/

        // notify indexer about shutdown
        _shutdownRequested = true;

        // wait until current timerTask is completed to allow a lucene to close all index writers
        LOG.info("Waiting for lucene to shutdown...");
        while (_indexerIsRunning) {
            // wait
            Thread.yield();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //ignore
            }
        }
        _timer = null;
        LOG.info("Lucene finished shutdown.");
    }
}