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.zenoss.jmxnl.NotificationListener.java

@SuppressWarnings("unchecked")
private void connect() throws IOException {
    log.info(url + ": Attempting connection (timeout in 180 seconds)");
    JMXConnector connector = JMXConnectorFactory.connect(url, environment);
    connector.addConnectionNotificationListener(this, null, "placeholder");
    MBeanServerConnection connection = connector.getMBeanServerConnection();

    log.info(url + ": Connected.");
    sendConnectionEvent("0", "JMX connection has been restored");

    Set<ObjectName> results = connection.queryNames(scope, null);
    java.util.Iterator<ObjectName> iter = results.iterator();
    while (iter.hasNext()) {
        ObjectName objName = (ObjectName) iter.next();
        String type = objName.getKeyProperty("type");
        if (type == null || !type.equals("alias")) {
            try {
                connection.addNotificationListener(objName, this, attributeFilter, zenossDevice);
                log.debug("Added notification listener: " + objName);
            } catch (IllegalArgumentException e) {
                log.debug("Can't listen to " + objName + " because it is not a notification broadcaster.");
            } catch (InstanceNotFoundException e) {
                log.debug("Can't listen to " + objName + " because it was not found on the server.");
            }//from  w  ww .  j a v a2 s .co m
        }

        // There can be a lot of listeners to add. Give other threads a
        // chance to get work done while this happens.
        Thread.yield();
    }
}

From source file:org.apache.http.contrib.benchmark.HttpBenchmark.java

private void execute() {

    prepare();/*from  w  w w  .j ava  2  s  .c o  m*/

    ThreadPoolExecutor workerPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                public Thread newThread(Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    BenchmarkWorker[] workers = new BenchmarkWorker[threads];
    for (int i = 0; i < threads; i++) {
        workers[i] = new BenchmarkWorker(params, verbosity, request[i], host, requests, keepAlive);
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < threads) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }

    workerPool.shutdown();
    ResultProcessor.printResults(workers, host, url.toString(), contentLength);
}

From source file:com.anysoftkeyboard.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
    //https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/433
    String stackTrace = Log.getStackTrace(ex);
    if (ex instanceof NullPointerException) {
        if (stackTrace.contains(
                "android.inputmethodservice.IInputMethodSessionWrapper.executeMessage(IInputMethodSessionWrapper.java")
                || stackTrace.contains(//  www  . j  a v  a 2  s.com
                        "android.inputmethodservice.IInputMethodWrapper.executeMessage(IInputMethodWrapper.java")) {
            Log.w(TAG, "An OS bug has been adverted. Move along, there is nothing to see here.");
            ignore = true;
        }
    } else if (ex instanceof java.util.concurrent.TimeoutException) {
        if (stackTrace.contains(".finalize")) {
            Log.w(TAG, "An OS bug has been adverted. Move along, there is nothing to see here.");
            ignore = true;
        }
    }

    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(mApp);
        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);
        final Parcelable reportDetailsExtra = new SendBugReportUiActivity.BugReportDetails(ex, logText);
        notificationIntent.putExtra(SendBugReportUiActivity.EXTRA_KEY_BugReportDetails, reportDetailsExtra);

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

        NotificationCompat.Builder builder = new NotificationCompat.Builder(mApp);
        builder.setSmallIcon(
                Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? R.drawable.notification_error_icon
                        : R.drawable.ic_notification_error)
                .setColor(ContextCompat.getColor(mApp, R.color.notification_background_error))
                .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.TESTING_BUILD ? 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(R.id.notification_icon_app_error, 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:org.eclipse.gyrex.jobs.internal.scheduler.Scheduler.java

private IStatus doRun(final IProgressMonitor monitor) {
    IExclusiveLock schedulerEngineLock = null;
    try {/*from www . j a  v  a 2  s .c om*/
        // get scheduler lock first
        // this ensures that there is at most one scheduler
        // engine is active in the whole cloud
        if (JobsDebug.schedulerEngine) {
            LOG.debug("Waiting for global scheduler engine lock.");
        }
        final ILockService lockService = JobsActivator.getInstance().getService(ILockService.class);
        while (schedulerEngineLock == null) {
            // check for cancellation
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            metrics.setStatus("WAITINGFORLOCK", "lock acquire loop");

            // try to acquire lock
            // (note, we cannot wait forever because we must check for cancelation regularly)
            // (however, checking very often is too expensive; we need to make a tradeoff here)
            // (randomizing might be a good strategy here; modifying the time here should also cause updates to the shutdown timeout in SchedulerApplication)
            try {
                schedulerEngineLock = lockService.acquireExclusiveLock(SCHEDULER_LOCK, null,
                        10000 + RandomUtils.nextInt(50000));
            } catch (final TimeoutException e) {
                // timeout waiting for lock
                // we simply keep on going as long as we aren't canceled
                Thread.yield();
            }
        }

        // check for cancellation
        if (monitor.isCanceled())
            throw new OperationCanceledException();

        metrics.setStatus("LOCKACQUIRED", "lock acquire loop");

        // setup the schedule listeners
        final IEclipsePreferences schedulesNode = ScheduleStore.getSchedulesNode();
        schedulesNode.addNodeChangeListener(this);

        // hook with all existing schedules
        for (final String scheduleStoreStorageKey : ScheduleStore.getSchedules()) {
            try {
                addSchedule(scheduleStoreStorageKey);
            } catch (final Exception e) {
                LOG.error("Unable to start schedule {}. {}", scheduleStoreStorageKey,
                        ExceptionUtils.getRootCauseMessage(e));
            }
        }

        // spin the loop while we are good to go
        while (schedulerEngineLock.isValid() && !monitor.isCanceled()) {
            Thread.sleep(1000L);
        }

        if (JobsDebug.schedulerEngine) {
            LOG.debug("Scheduler engine canceled. Shutting down.");
        }
    } catch (final IllegalStateException e) {
        metrics.setStatus("ERROR", ExceptionUtils.getRootCauseMessage(e));
        LOG.warn("Unable to check for schedules. System does not seem to be ready. {}",
                ExceptionUtils.getRootCauseMessage(e));
        return Status.CANCEL_STATUS;
    } catch (final InterruptedException e) {
        metrics.setStatus("INTERRUPTED", ExceptionUtils.getRootCauseMessage(e));
        Thread.currentThread().interrupt();
        return Status.CANCEL_STATUS;
    } catch (final BackingStoreException e) {
        metrics.setStatus("ERROR", ExceptionUtils.getRootCauseMessage(e));
        LOG.error("Error reading schedules. {}", ExceptionUtils.getRootCauseMessage(e));
        return Status.CANCEL_STATUS;
    } finally {
        try {
            // remove listener
            try {
                ScheduleStore.getSchedulesNode().removeNodeChangeListener(this);
            } catch (final Exception e) {
                // might already be going down
            }

            // bring down all schedules
            final Collection<Schedule> schedules = schedulesById.values();
            for (final Schedule schedule : schedules) {
                try {
                    schedule.stop();
                } catch (final Exception e) {
                    // ignore
                }
            }
            schedulesById.clear();
        } finally {
            // release lock
            if (null != schedulerEngineLock) {
                try {
                    schedulerEngineLock.release();
                } catch (final Exception e) {
                    // ignore
                }
            }
        }
    }

    return Status.OK_STATUS;
}

From source file:Main.java

/**
 * Compute the natural logarithm of x to a given scale, x > 0.
 * Use Newton's algorithm./*from   w  ww  .  ja v  a 2s.  c o  m*/
 */
private static BigDecimal lnNewton(BigDecimal x, int scale) {
    int sp1 = scale + 1;
    BigDecimal n = x;
    BigDecimal term;

    // Convergence tolerance = 5*(10^-(scale+1))
    BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);

    // Loop until the approximations converge
    // (two successive approximations are within the tolerance).
    do {

        // e^x
        BigDecimal eToX = exp(x, sp1);

        // (e^x - n)/e^x
        term = eToX.subtract(n).divide(eToX, sp1, BigDecimal.ROUND_DOWN);

        // x - (e^x - n)/e^x
        x = x.subtract(term);

        Thread.yield();
    } while (term.compareTo(tolerance) > 0);

    return x.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
}

From source file:org.kantega.dogmaticmvc.web.DogmaticMVCHandler.java

public static void copy(InputStream in, OutputStream out) throws IOException {
    byte[] buf = new byte[1024];
    while (true) {
        int count = in.read(buf, 0, buf.length);
        if (count == -1)
            break;
        if (count == 0) {
            Thread.yield();
            continue;
        }//  w w w . j  ava 2s  .  co m
        out.write(buf, 0, count);
    }
}

From source file:com.auditbucket.test.functional.TestForceDeadlock.java

/**
 * Multi threaded test that tests to make sure duplicate Doc Types and Headers are not created
 *
 * @throws Exception// w  w w. j ava  2  s .  c o  m
 */
@Test
public void metaHeaderUnderLoad() throws Exception {
    cleanUpGraph(); // No transaction so need to clear down the graph

    String monowai = "Monowai";
    regService.registerSystemUser(new RegistrationBean(monowai, mike, "bah"));
    SecurityContextHolder.getContext().setAuthentication(authMike);
    Fortress fortress = fortressService.registerFortress("auditTest" + System.currentTimeMillis());
    String docType = "TestAuditX";

    CountDownLatch latch = new CountDownLatch(4);
    ArrayList<TagInputBean> tags = getTags(10);

    Map<Integer, CallerRefRunner> runners = new HashMap<>();
    int threadMax = 15;
    for (int i = 0; i < threadMax; i++) {
        runners.put(i, addRunner(fortress, docType, "ABC" + i, 20, tags, latch));
    }

    latch.await();
    boolean working = false;
    Map<Integer, Future<Integer>> futures = new HashMap<>();
    String apiKey = fortress.getCompany().getApiKey();
    try {
        for (int i = 0; i < threadMax; i++) {
            futures.put(i, trackEP.trackHeadersAsync(runners.get(i).getInputBeans(), true, apiKey));
        }
        working = true;
    } catch (RuntimeException e) {
        logger.error("rte ", e);
    }
    for (int i = 0; i < threadMax; i++) {
        if (futures.get(i) != null) {
            while (!futures.get(i).isDone()) {
                Thread.yield();
            }
            doFutureWorked(futures.get(i), runners.get(i).getMaxRun());
        }
    }
    assertEquals(true, working);
    assertNotNull(tagService.findTag(fortress.getCompany(), tags.get(0).getName(), tags.get(0).getIndex()));

    Map<String, Tag> createdTags = tagService.findTags(fortress.getCompany(), tags.get(0).getIndex());
    assertEquals(false, createdTags.isEmpty());
    assertEquals(10, createdTags.size());
}

From source file:org.apache.zeppelin.helium.HeliumApplicationFactoryTest.java

@Test
public void testLoadRunUnloadApplication() throws IOException, ApplicationException, InterruptedException {
    // given//from  w ww  . j  a v a  2s  .c om
    HeliumPackage pkg1 = new HeliumPackage(HeliumType.APPLICATION, "name1", "desc1", "",
            HeliumTestApplication.class.getName(), new String[][] {}, "", "");

    Note note1 = notebook.createNote(anonymous);
    interpreterSettingManager.setInterpreters("user", note1.getId(),
            interpreterSettingManager.getDefaultInterpreterSettingList());

    Paragraph p1 = note1.addParagraph(AuthenticationInfo.ANONYMOUS);

    // make sure interpreter process running
    p1.setText("%mock1 job");
    p1.setAuthenticationInfo(anonymous);
    note1.run(p1.getId());
    while (p1.isTerminated() == false || p1.getResult() == null)
        Thread.yield();

    assertEquals("repl1: job", p1.getResult().message().get(0).getData());

    // when
    assertEquals(0, p1.getAllApplicationStates().size());
    String appId = heliumAppFactory.loadAndRun(pkg1, p1);
    assertEquals(1, p1.getAllApplicationStates().size());
    ApplicationState app = p1.getApplicationState(appId);
    Thread.sleep(500); // wait for enough time

    // then
    assertEquals("Hello world 1", app.getOutput());

    // when
    heliumAppFactory.run(p1, appId);
    Thread.sleep(500); // wait for enough time

    // then
    assertEquals("Hello world 2", app.getOutput());

    // clean
    heliumAppFactory.unload(p1, appId);
    notebook.removeNote(note1.getId(), anonymous);
}

From source file:com.openteach.diamond.network.waverider.network.Packet.java

/**
 * ??Packet, ??//from w w w . jav  a 2s .c o m
 * @param inputBuffer
 * @return
 * @throws IOException, InterruptedException
 */
public static Packet parse(BlockingQueue<ByteBuffer> inputBuffer, NetWorkEndPoint endPoint,
        SocketChannel channel) throws IOException, InterruptedException {
    // Buffer for packet header
    byte[] tmpBuf = new byte[NetWorkConstants.DEFAULT_NETWORK_BUFFER_SIZE];
    ByteBuffer header = ByteBuffer.allocate(Packet.getHeaderSize());
    ByteBuffer currentBuffer = null;
    int rest = 0;
    boolean isRemove = false;

    // ?
    while (true) {
        while ((currentBuffer = inputBuffer.peek()) == null) {
            if (!endPoint.notifyRead(channel)) {
                throw new IOException("Socket closed by other thread");
            }
            // ?
            //endPoint.waitMoreData(5);
            // FIXME 2ms
            //Thread.sleep(1);
            Thread.yield();
        }
        isRemove = false;
        rest = header.capacity() - header.position();
        if (currentBuffer.remaining() >= rest) {
            if (currentBuffer.remaining() == rest) {
                isRemove = true;
            }
            currentBuffer.get(tmpBuf, 0, rest);
            header.put(tmpBuf, 0, rest);
            if (isRemove) {
                inputBuffer.remove();
            }
            break;
        } else {
            header.put(currentBuffer);
            inputBuffer.remove();
        }
    }

    header.flip();

    // , ???

    // ?
    Integer size = header.getInt(Packet.getLengthPosition());
    // For test
    /*if(size < 0 || size > 100000) {
       logger.info("Error");
    }*/
    //logger.debug(new StringBuilder("Try to allocate ").append(size).append(" bytes memory"));
    ByteBuffer buffer = ByteBuffer.allocate(size);
    buffer.put(header);
    header.clear();

    // ?
    while (true) {
        while ((currentBuffer = inputBuffer.peek()) == null) {
            endPoint.notifyRead(channel);
            Thread.sleep(1000);
        }
        isRemove = false;
        rest = buffer.capacity() - buffer.position();
        if (currentBuffer.remaining() >= rest) {
            if (currentBuffer.remaining() == rest) {
                isRemove = true;
            }
            currentBuffer.get(tmpBuf, 0, rest);
            buffer.put(tmpBuf, 0, rest);
            if (isRemove) {
                inputBuffer.remove();
            }
            break;
        } else {
            buffer.put(currentBuffer);
            inputBuffer.remove();
        }
    }
    //buffer.position(0);
    buffer.flip();
    Packet packet = Packet.unmarshall(buffer);
    //logger.info("Parse one packet from network");
    //packet.dump();
    return packet;
}

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

private static Response putValueXML(String url, String table, String row, String column, String value)
        throws IOException, JAXBException {
    RowModel rowModel = new RowModel(row);
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value)));
    CellSetModel cellSetModel = new CellSetModel();
    cellSetModel.addRow(rowModel);/*from   w  w  w .jav  a  2s .co  m*/
    StringWriter writer = new StringWriter();
    marshaller.marshal(cellSetModel, writer);
    Response response = client.put(url, Constants.MIMETYPE_XML, Bytes.toBytes(writer.toString()));
    Thread.yield();
    return response;
}