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.auditbucket.test.functional.TestForceDeadlock.java

@Test
public void tagsUnderLoad() 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());

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

    Map<Integer, TagRunner> runners = new HashMap<>();
    int threadMax = 3;
    boolean worked = true;
    for (int i = 0; i < threadMax; i++) {
        runners.put(i, addTagRunner(fortress, 5, tags, latch));
    }/*  w  ww.ja  v a 2s  .c om*/

    //latch.await();
    for (int i = 0; i < threadMax; i++) {
        while (runners.get(i) == null || !runners.get(i).isDone()) {
            Thread.yield();
        }
        assertEquals("Error occurred creating tags under load", true, runners.get(i).isWorked());
    }
    assertEquals(true, worked);
}

From source file:org.osaf.cosmo.filters.RetryFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String method = httpRequest.getMethod();

    // only care about certain methods
    if (isFilterMethod(method)) {
        // Wrap request so we can buffer the request in the event
        // it needs to be retried.  If the request isn't buffered,
        // then we can't consume the servlet inputstream again.
        request = new BufferedRequestWrapper((HttpServletRequest) request, maxMemoryBuffer);

        // Wrap response so we can trap any 500 responses before they
        // get to the client
        response = new ResponseErrorWrapper((HttpServletResponse) response);

        int attempts = 0;

        while (attempts <= maxRetries) {

            Exception ex = null;//  www  .  j  a v a 2  s.c  o m

            try {
                chain.doFilter(request, response);
            } catch (RuntimeException e) {
                // Catch runtime exceptions
                if (isFilterException(e)) {
                    ex = e;
                } else {
                    log.error("the server encountered an unexpected error", e);
                    sendError((ResponseErrorWrapper) response);
                }
            }

            // If we didn't catch it, then look for the exception
            // in the request attributes
            if (ex == null)
                ex = findFilterException(httpRequest);

            // If there was an exception that we were looking for
            // (either caught or found in the request), then prepare
            // to retry.
            if (ex != null) {
                attempts++;

                // Fail after maxRetries attempts
                if (attempts > maxRetries) {
                    log.error("reached maximum retries for " + httpRequest.getMethod() + " "
                            + httpRequest.getRequestURI());
                    if (!((ResponseErrorWrapper) response).flushError())
                        sendError((ResponseErrorWrapper) response);
                }
                // Otherwise, prepare to retry
                else {
                    log.warn("caught: " + ex.getMessage() + " : retrying request " + httpRequest.getMethod()
                            + " " + httpRequest.getRequestURI() + " " + attempts);
                    ((ResponseErrorWrapper) response).clearError();
                    ((BufferedRequestWrapper) request).retryRequest();
                    Thread.yield();
                }
            }
            // Otherwise flush the error if necessary and
            // proceed as normal.
            else {
                ((ResponseErrorWrapper) response).flushError();
                return;
            }
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:at.uni_salzburg.cs.ckgroup.apos.AposNtripCasterMock.java

/**
 * This method creates the NTRIP caster thread and starts it.
 *
 * @throws IllegalStateException thrown if the mail server already runs
 *//*w  w w  . j  a  va2s . c  o m*/
public void startCasterThread() throws IllegalStateException {
    System.out.println("Start Mailserver on port " + port);
    if (ntripCaster != null)
        throw new IllegalStateException("NTRIP caster is already running.");

    ntripCasterRunning = false;

    ntripCaster = new NtripCasterThread();
    ntripCaster.start();

    // Now we wait for the NTRIP caster to open its socket.
    int cycles = 100;
    while (!ntripCasterRunning && --cycles > 0) {
        try {
            Thread.sleep(50);
        } catch (Exception e) {
        }
        Thread.yield();
    }

    if (cycles == 0)
        throw new IllegalStateException("Can not launch NTRIP caster.");
}

From source file:com.indeed.lsmtree.recordlog.TestRecordLogDirectory.java

public void testRandom() throws Exception {
    final RecordLogDirectory<String> fileCache = createRecordLogDirectory();
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < 8; i++) {
        final int index = i;
        new Thread(new Runnable() {
            @Override//from w  w  w . j a v a  2s . c o  m
            public void run() {
                try {
                    final Random r = new Random(index);
                    for (int i = 0; i < 10000; i++) {
                        int rand = r.nextInt(positions.size());
                        assertTrue(fileCache.get(positions.get(rand)).equals(strings.get(rand)));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    fileCache.close();
}

From source file:com.stainlesscode.mediapipeline.demux.EventAwareSimpleDemultiplexer.java

@SuppressWarnings("unchecked")
protected void demultiplexerLoop() throws NoSuchElementException, IllegalStateException, Exception {
    if (LogUtil.isDebugEnabled())
        LogUtil.debug("In demultiplexerLoop()");

    int result = -1;

    if (packet == null) {
        packet = (IPacket) engineRuntime.getPacketPool().borrowObject();

        engineRuntime.getContainerLock().lock();
        try {// w ww .j a  v a  2  s  .c om
            result = engineRuntime.getContainer().readNextPacket(packet);
            if (LogUtil.isDebugEnabled())
                LogUtil.debug(
                        "read packet " + packet.getTimeStamp() + " for stream " + packet.getStreamIndex());
        } finally {
            engineRuntime.getContainerLock().unlock();
        }
    } else {
        result = 0;
    }

    if (result >= 0) {
        if (packet != null) {
            if (LogUtil.isDebugEnabled())
                LogUtil.debug("extracting packet to buffer " + packet.getStreamIndex());
            Buffer destinationBuffer = engineRuntime.getStreamToBufferMap().get(packet.getStreamIndex());

            if (destinationBuffer == null) {
                packet = null;
            } else {
                try {
                    destinationBuffer.add(packet.copyReference());
                    packet = null;
                } catch (BufferOverflowException e) {
                    Thread.yield();
                }
            }
        }
    } else {
        LogUtil.error("result is " + result);
        if (result == -32) {
            // System.out.println("CLIP_END detected, firing event");
            // engineRuntime.getPlayer().fireMediaPlayerEvent(
            // new MediaPlayerEvent(engineRuntime.getPlayer(),
            // MediaPlayerEvent.CLIP_END));
            setMarkedForDeath(true);
        }
        IError error = IError.make(result);
        LogUtil.error("ERROR: " + error.getDescription());
    }
}

From source file:org.apache.streams.elasticsearch.ElasticsearchPersistReader.java

protected void write(StreamsDatum entry) {
    boolean success;
    do {/*from  w ww . ja v a2  s  .co m*/
        try {
            lock.readLock().lock();
            success = persistQueue.offer(entry);
            Thread.yield();
        } finally {
            lock.readLock().unlock();
        }
    } while (!success);
}

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

static Response putValuePB(String url, String table, String row, String column, String value)
        throws IOException {
    RowModel rowModel = new RowModel(row);
    rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value)));
    CellSetModel cellSetModel = new CellSetModel();
    cellSetModel.addRow(rowModel);//  w  ww .ja  v a  2s.c om
    Response response = client.put(url, Constants.MIMETYPE_PROTOBUF, cellSetModel.createProtobufOutput());
    Thread.yield();
    return response;
}

From source file:org.mule.test.routing.UntilSuccessfulTestCase.java

private void ponderUntilMessageCountReceivedByCustomMP(final int expectedCount) throws InterruptedException {
    while (CustomMP.getCount() < expectedCount) {
        Thread.yield();
        Thread.sleep(100L);//from  w w w  . j a  v a  2  s  .  co  m
    }
}

From source file:org.unitedinternet.cosmo.filters.RetryFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // only care about certain methods
    if (isFilterMethod(request) && response instanceof HttpServletResponse
            && request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // Wrap request so we can buffer the request in the event
        // it needs to be retried.  If the request isn't buffered,
        // then we can't consume the servlet inputstream again.
        request = new BufferedRequestWrapper(httpRequest, maxMemoryBuffer);

        // Wrap response so we can trap any 500 responses before they
        // get to the client
        response = new ResponseErrorWrapper(httpResponse);

        int attempts = 0;

        while (attempts <= maxRetries) {

            Exception ex = null;/*  ww w.  ja v a  2  s  . co m*/

            try {
                chain.doFilter(request, response);
            } catch (RuntimeException e) {
                // Catch runtime exceptions
                if (isFilterException(e)) {
                    ex = e;
                } else {
                    LOG.error("the server encountered an unexpected error", e);
                    sendError((ResponseErrorWrapper) response);
                }
            }

            // If we didn't catch it, then look for the exception
            // in the request attributes
            if (ex == null) {
                ex = findFilterException(httpRequest);
            }

            // If there was an exception that we were looking for
            // (either caught or found in the request), then prepare
            // to retry.
            if (ex != null) {
                attempts++;

                // Fail after maxRetries attempts
                if (attempts > maxRetries) {
                    //Fix Log Forging - java fortify
                    //Writing unvalidated user input to log files can allow an attacker
                    //to forge log entries or inject malicious content into the logs.
                    LOG.error("reached maximum retries for " + httpRequest.getMethod() + " "
                            + httpRequest.getRequestURI());
                    if (!((ResponseErrorWrapper) response).flushError()) {
                        sendError((ResponseErrorWrapper) response);
                    }
                }
                // Otherwise, prepare to retry
                else {
                    LOG.warn("caught: " + ex.getMessage() + " : retrying request " + httpRequest.getMethod()
                            + " " + httpRequest.getRequestURI() + " " + attempts);
                    ((ResponseErrorWrapper) response).clearError();
                    ((BufferedRequestWrapper) request).retryRequest();
                    Thread.yield();
                }
            }
            // Otherwise flush the error if necessary and
            // proceed as normal.
            else {
                ((ResponseErrorWrapper) response).flushError();
                return;
            }
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:pt.ua.dicoogle.core.index.FileIndexer.java

/**
 * Index a given file//from   w  w w .  j  a va2s  .  c  o m
 * @param writer Object that represents an index opened for writting
 * @param file File to index
 */
public void index(File file, boolean resume) throws FileHandlerException {
    if (file.canRead()) {
        if (file.isDirectory()) {
            String[] files = file.list();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    try {

                        // Leave processor
                        Thread.yield();
                        // IDLE - Free CPU for a while
                        if (Settings.getInstance().getIndexerEffort() < 100) {
                            Thread.sleep((100 - Settings.getInstance().getIndexerEffort()) * 20);
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(FileIndexer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    index(new File(file, files[i]), resume);

                }
            }
        } else {
            boolean zip = false;
            /* Verify if zip is enable */
            if (Settings.getInstance().isIndexZIPFiles()) {
                if (file.getAbsolutePath().endsWith(".zip")) {
                    zip = true;
                    FileInputStream fis = null;
                    ZipInputStream zis = null;
                    ZipEntry entry;
                    try {

                        fis = new FileInputStream(file.getAbsolutePath());
                        zis = new ZipInputStream(new BufferedInputStream(fis));

                        //
                        // Read each entry from the ZipInputStream until no more entry found
                        // indicated by a null return value of the getNextEntry() method.
                        //
                        while ((entry = zis.getNextEntry()) != null) {
                            //System.out.println("Unzipping: " + entry.getName());

                            int size;
                            byte[] buffer = new byte[2048];

                            FileOutputStream fos = new FileOutputStream(entry.getName());
                            BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);

                            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                                bos.write(buffer, 0, size);
                            }
                            bos.flush();
                            bos.close();
                            fos.close();
                            File tmpFile = new File(entry.getName());
                            putFileIndex(tmpFile, resume);

                            tmpFile.delete();

                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            zis.close();
                            fis.close();
                            //System.out.println("Closing File...");
                        } catch (IOException ex) {
                            Logger.getLogger(FileIndexer.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }

                }
            }
            if (!zip)
                putFileIndex(file, resume);

        }
    }
}