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.yahoo.ycsb.db.couchbase2.Couchbase2Client.java

@Override
public int calculateStrategy(final IntSupplier supplier, final boolean hasTasks) throws Exception {
    int selectNowResult = supplier.get();
    if (hasTasks || selectNowResult != 0) {
        counter = 0;//from   w  w w  .ja v a 2  s  .  c o m
        return selectNowResult;
    }
    counter++;

    if (counter > 2000) {
        LockSupport.parkNanos(1);
    } else if (counter > 3000) {
        Thread.yield();
    } else if (counter > 4000) {
        LockSupport.parkNanos(1000);
    } else if (counter > 5000) {
        // defer to blocking select
        counter = 0;
        return SelectStrategy.SELECT;
    }

    return SelectStrategy.CONTINUE;
}

From source file:com.clark.func.Functions.java

public static void currentYield() {
    Thread.yield();
}

From source file:org.jcurl.demo.tactics.JCurlShotPlanner.java

private Cursor switchCursor(final Cursor neo) {
    final Cursor cu = getMainFrame().getCursor();
    getMainFrame().setCursor(neo);//from   w w w .ja va 2 s  .  c  o m
    Thread.yield();
    return cu;
}

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

/**
 * Re-indexes the full JCR sub-tree, starting from the specified node.
 *
 * @param startNodeId the UUID of the node to start re-indexing with
 * @throws RepositoryException if an error occurs while indexing a node.
 * @throws NoSuchItemStateException in case of JCR errors
 * @throws IllegalArgumentException in case of JCR errors
 * @throws ItemStateException in case of JCR errors
 * @throws IOException if an error occurs while updating the index
 *///w w w .ja v a  2s  .  com
public void reindexTree(String startNodeId) throws RepositoryException, NoSuchItemStateException,
        IllegalArgumentException, ItemStateException, IOException {
    long startTime = System.currentTimeMillis();
    log.info("Requested re-indexing of the JCR tree for node {}", startNodeId);
    ItemStateManager stateManager = getContext().getItemStateManager();
    List<NodeState> nodes = new LinkedList<>();
    collectChildren((NodeState) stateManager.getItemState(NodeId.valueOf(startNodeId)), stateManager, nodes);

    int totalCount = nodes.size();
    log.info("Collected {} node IDs to be re-indexed", totalCount);

    List<NodeId> removed = new LinkedList<>();
    for (NodeState n : nodes) {
        removed.add(n.getNodeId());
    }

    if (totalCount > batchSize) {
        // will process in batches
        log.info("Will process re-indexig of nodes in batches of {} nodes", batchSize);
        int listStart = 0;
        int listEnd = Math.min(totalCount, batchSize);
        while (listStart < totalCount) {
            if (listStart > 0) {
                Thread.yield();
            }
            super.updateNodes(removed.subList(listStart, listEnd).iterator(),
                    nodes.subList(listStart, listEnd).iterator());

            if (listEnd % (10 * batchSize) == 0) {
                log.info("Re-indexed {} nodes out of {}", listEnd, totalCount);
            }

            listStart += batchSize;
            listEnd = Math.min(totalCount, listEnd + batchSize);
        }
    } else {
        super.updateNodes(removed.iterator(), nodes.iterator());
    }

    log.info("Done re-indexed JCR sub-tree for node {} in {} ms", startNodeId,
            System.currentTimeMillis() - startTime);
}

From source file:org.flockdata.test.integration.Helper.java

/**
 * Processing delay for threads and integration to complete. If you start getting sporadic
 * Heuristic exceptions, chances are you need to call this routine to give other threads
 * time to commit their work.//from   w  ww .  j a  v a  2 s  .  com
 * Likewise, waiting for results from fd-search can take a while. We can't know how long this
 * is so you can experiment on your own environment by passing in -DsleepSeconds=1
 *
 * @param milliseconds to pause for
 * @throws Exception
 */
public static void waitAWhile(String message, long milliseconds) throws Exception {
    logger.debug(message, milliseconds / 1000d);
    Thread.yield();
    Thread.sleep(milliseconds);

}

From source file:org.apache.hadoop.hbase.master.TestDistributedLogSplitting.java

/**
 * The original intention of this test was to force an abort of a region
 * server and to make sure that the failure path in the region servers is
 * properly evaluated. But it is difficult to ensure that the region server
 * doesn't finish the log splitting before it aborts. Also now, there is
 * this code path where the master will preempt the region server when master
 * detects that the region server has aborted.
 * @throws Exception/*from   w w w  .ja v  a  2s . co m*/
 */
@Test(timeout = 300000)
public void testWorkerAbort() throws Exception {
    LOG.info("testWorkerAbort");
    startCluster(3);
    final int NUM_LOG_LINES = 10000;
    final SplitLogManager slm = master.getMasterFileSystem().splitLogManager;
    FileSystem fs = master.getMasterFileSystem().getFileSystem();

    final List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
    HRegionServer hrs = findRSToKill(false, "table");
    Path rootdir = FSUtils.getRootDir(conf);
    final Path logDir = new Path(rootdir, HLogUtil.getHLogDirectoryName(hrs.getServerName().toString()));

    installTable(new ZooKeeperWatcher(conf, "table-creation", null), "table", "family", 40);

    makeHLog(hrs.getWAL(), ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices()), "table", "family",
            NUM_LOG_LINES, 100);

    new Thread() {
        public void run() {
            waitForCounter(tot_wkr_task_acquired, 0, 1, 1000);
            for (RegionServerThread rst : rsts) {
                rst.getRegionServer().abort("testing");
                break;
            }
        }
    }.start();
    // slm.splitLogDistributed(logDir);
    FileStatus[] logfiles = fs.listStatus(logDir);
    TaskBatch batch = new TaskBatch();
    slm.enqueueSplitTask(logfiles[0].getPath().toString(), batch);
    //waitForCounter but for one of the 2 counters
    long curt = System.currentTimeMillis();
    long waitTime = 80000;
    long endt = curt + waitTime;
    while (curt < endt) {
        if ((tot_wkr_task_resigned.get() + tot_wkr_task_err.get() + tot_wkr_final_transition_failed.get()
                + tot_wkr_task_done.get() + tot_wkr_preempt_task.get()) == 0) {
            Thread.yield();
            curt = System.currentTimeMillis();
        } else {
            assertTrue(1 <= (tot_wkr_task_resigned.get() + tot_wkr_task_err.get()
                    + tot_wkr_final_transition_failed.get() + tot_wkr_task_done.get()
                    + tot_wkr_preempt_task.get()));
            return;
        }
    }
    fail("none of the following counters went up in " + waitTime + " milliseconds - "
            + "tot_wkr_task_resigned, tot_wkr_task_err, "
            + "tot_wkr_final_transition_failed, tot_wkr_task_done, " + "tot_wkr_preempt_task");
}

From source file:org.flockdata.test.integration.Helper.java

static EntityLog waitForLogCount(Company company, Entity entity, int expectedCount, EntityService entityService)
        throws Exception {
    // Looking for the first searchKey to be logged against the entity
    int i = 0;/* w w  w . j  a  v  a2  s .c o m*/
    int timeout = 100;
    int count = 0;

    while (i <= timeout) {
        Entity updatedEntity = entityService.getEntity(company, entity.getKey());
        count = entityService.getLogCount(company, updatedEntity.getKey());

        EntityLog log = entityService.getLastEntityLog(company, updatedEntity.getKey());
        // We have at least one log?
        if (count == expectedCount)
            return log;
        Thread.yield();
        //            if (i > 20)
        //                waitAWhile("Waiting {} seconds for the log to update");
        i++;
    }
    if (i > 22)
        logger.info("Wait for log got to [{}] for entityId [{}]", i, entity.getId());
    throw new Exception(String.format("Timeout waiting for the requested log count of %s. Got to %s",
            expectedCount, count));
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

/**
 * This method sets the percentage completion of a particular workflow
 * // ww  w .j a va  2  s  .  c  om
 * @param p_destinationArrow
 *            - The name of the outgoing arrow of a condition node (if the
 *            next node of this task is a condition node). This is used for
 *            making decision.
 * @param skipping
 *            Indicates this task is being skipped.
 * 
 * @throws RemoteException
 *             , WorkflowManagerException
 */
public void setTaskCompletion(String p_userId, Task p_task, String p_destinationArrow, String skipping)
        throws RemoteException, WorkflowManagerException {
    if (s_logger.isDebugEnabled()) {
        String s = "null task";
        if (p_task != null)
            s = p_task.toString();
    }

    for (int i = 0; i < 3; i++) {
        try {
            completeTask(p_userId, p_task, p_destinationArrow, skipping);
            break;
        } catch (Exception e) {
            s_logger.warn("Ignoring Exception");
            Thread.yield();
        }
    }

    // for COTI api finish job
    try {
        Workflow wfClone = (Workflow) p_task.getWorkflow();
        JobImpl curJob = HibernateUtil.get(JobImpl.class, wfClone.getJob().getId());
        String jobStatus = curJob.getState();
        if (Job.LOCALIZED.equals(jobStatus) || Job.EXPORTED.equals(jobStatus)
                || Job.EXPORTING.equals(jobStatus)) {
            COTIUtilEnvoy.finishCOTIJob(curJob);
        }
    } catch (Throwable t) {
        // log the error but don't let it affect job completion
        s_logger.error("Error trying to finish COTI job.", t);
    }

    try {
        long jobId = p_task.getJobId();
        L10nProfile l10nProfile = ServerProxy.getJobHandler().getL10nProfileByJobId(jobId);
        long wfStatePostId = l10nProfile.getWfStatePostId();
        if (wfStatePostId != -1) {
            WfStatePostThread myTask = new WfStatePostThread(p_task, p_destinationArrow, false);
            Thread t = new MultiCompanySupportedThread(myTask);
            t.start();
        }
    } catch (Exception e) {
        s_logger.error("Error trying to finish COTI job.", e);
    }
}

From source file:org.xmlsh.sh.shell.Shell.java

public void killChild(ShellThread job, long waitTime) {
    if (job != Thread.currentThread()) {
        if (job.isAlive()) {
            try {
                job.shutdown(true, waitTime);
            } catch (Exception e) {

                getLogger().warn("Exception trying to close child shell: " + job.describe());
            }/*from   ww  w .  j av  a 2s . c om*/
        } else
            job.interrupt();

        Thread.yield();
        if (waitTime >= 0) {
            try {
                job.join(waitTime);
            } catch (InterruptedException e) {
                getLogger().warn("Exception trying to wait for shell: " + job.describe());
            }
        }
        Thread.yield();

        if (job.isAlive())
            getLogger().warn("Failed to kill child shell: " + job.describe());
    }
}

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

/**
 * places a lock on this object/*  ww  w .  j  av  a2  s  .c om*/
 * @param isDeep if true this lock will apply to this node and all its descendants; if false, it applies only to
 * this node.
 * @param isSessionScoped if true, this lock expires with the current session; if false it expires when explicitly
 * or automatically unlocked for some other reason.
 * @param yieldFor number of milliseconds for which this method will try to get a lock
 * @return A Lock object containing a lock token.
 * @throws LockException if this node is already locked or <code>isDeep</code> is true and a descendant node of
 * this node already holds a lock.
 * @throws RepositoryException if an error occurs
 * @see javax.jcr.Node#lock(boolean, boolean)
 */
public Lock lock(boolean isDeep, boolean isSessionScoped, long yieldFor)
        throws LockException, RepositoryException {
    long finalTime = System.currentTimeMillis() + yieldFor;
    LockException lockException = null;
    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;
}