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:uk.ac.dundee.computing.SensorSimulator.DeviceThread.java

public void run() {
    //while (running) {
    for (int Count = 0; Count < readingCount; Count++) {
        if (Count % 10 == 0) {
            System.out.println(dd.getInsertion_time() + " :: " + dd.getDevice() + " : " + Count + " :: " + ip);
        }//from   w  ww  .j a v a2s.c om
        Sensor sensors[] = dd.getSensors();
        JSONArray jsonSensors = new JSONArray();
        JSONObject Record = null;
        for (int i = 0; i < sensors.length; i++) {
            int type = sensors[i].getType();
            Object value = sensors[i].getValue();
            Record = new JSONObject();
            Record.put("name", sensors[i].getName());
            switch (type) {
            case 1:
                Float fValue = (Float) value;
                //System.out.println(sensors[i].getName() + ":" + fValue);

                Record.put("fValue", fValue.toString());
                break;
            case 2:
                Integer iValue = (Integer) value;
                //System.out.println(sensors[i].getName() + ":" + iValue);
                Record.put("iValue", iValue.toString());
                break;
            case 3:
                Record.put("sValue", (String) value);
            default:
                //System.out.println("Type" + type);
                break;
            }
            jsonSensors.put(Record);
        }

        JSONObject jsonDevice = new JSONObject();
        jsonDevice.put("device", dd.getDevice());
        jsonDevice.put("insertion_time", dd.getInsertion_time());
        JSONObject jsonMeta = new JSONObject();
        Map<String, String> meta = dd.getMeta();
        for (Map.Entry<String, String> entry : meta.entrySet()) {
            jsonMeta.put(entry.getKey(), entry.getValue());
        }

        JSONObject json = new JSONObject();
        json.put("sensors", jsonSensors);
        json.put("SensorData", jsonDevice);
        json.put("meta", jsonMeta);

        //System.out.println(dd.getDevice());
        Socket sc = null;
        boolean sent = false;
        while (sent == false) {
            try {
                sc = new Socket(ip, 19877);
                OutputStream os = sc.getOutputStream();
                PrintWriter out = new PrintWriter(os);
                out.print(json);
                out.print("\r\n");
                out.close();
                sc.close();
                sent = true;
            } catch (Exception et) {
                System.out.println("No Host " + dd.getDevice() + " : " + ip);
                try {
                    Thread.sleep((long) 1000);
                } catch (Exception et1) {
                    System.out.println("Cant sleep " + et);
                }
            }
        }
        try {
            //System.out.println("Sleeping");
            Thread.sleep(Millis);
            Thread.yield();
        } catch (Exception et) {
            System.out.println("Sleep went wrong");
        }

    }

}

From source file:org.sakaiproject.search.indexer.impl.test.SequenceGeneratorDisabled.java

/**
 * Test method for/* w  w  w .  j a va2s .c o  m*/
 * {@link org.sakaiproject.search.transaction.impl.TransactionSequenceImpl#getNextId()}.
 */
public final void testGetNextId() {

    log.info("================================== " + this.getClass().getName() + ".testGetNextId");
    nt = 0;
    fail = 0;
    final ConcurrentHashMap<Long, Long> m = new ConcurrentHashMap<Long, Long>();
    for (int i = 0; i < 20; i++) {
        Thread t = new Thread(new Runnable() {

            public void run() {
                try {
                    nt++;
                    long n = 0;
                    Map<Long, Long> seq = new HashMap<Long, Long>();
                    for (int i = 0; i < 1000; i++) {
                        n = sequenceGenerator.getNextId();
                        if (seq.get(n) != null) {
                            fail = n;
                            fail("Local clash on " + n);

                        }
                        seq.put(n, n);
                    }
                    log.debug("Last " + n);
                    for (long nx : seq.values()) {
                        if (m.get(nx) != null) {
                            fail = nx;
                            fail("Concurrent clash on " + nx);
                        }
                        m.put(nx, nx);
                    }
                } finally {
                    nt--;
                }

            }

        });
        t.start();
    }
    while (nt > 0) {
        if (fail != 0) {
            fail("Failed with clash on " + fail);
        }
        Thread.yield();
    }
    log.info("==PASSED========================== " + this.getClass().getName() + ".testGetNextId");

}

From source file:com.bt.download.android.gui.httpserver.DownloadHandler.java

public void internalHandler(HttpExchange exchange) throws IOException {
    assertUPnPActive();/*ww  w .ja va 2  s.  c  o m*/

    OutputStream os = null;
    FileInputStream fis = null;

    byte type = -1;
    int id = -1;

    PeerHttpUpload upload = null;

    try {

        List<NameValuePair> query = URLEncodedUtils.parse(exchange.getRequestURI(), "UTF-8");

        for (NameValuePair item : query) {
            if (item.getName().equals("type")) {
                type = Byte.parseByte(item.getValue());
            }
            if (item.getName().equals("id")) {
                id = Integer.parseInt(item.getValue());
            }
        }

        if (type == -1 || id == -1) {
            exchange.sendResponseHeaders(Code.HTTP_BAD_REQUEST, 0);
            return;
        }

        if (TransferManager.instance().getActiveUploads() >= ConfigurationManager.instance()
                .maxConcurrentUploads()) {
            sendBusyResponse(exchange);
            return;
        }

        FileDescriptor fd = Librarian.instance().getFileDescriptor(type, id);
        if (fd == null) {
            throw new IOException("There is no such file shared");
        }

        upload = TransferManager.instance().upload(fd);

        exchange.getResponseHeaders().add("Content-Type", fd.mime);
        exchange.sendResponseHeaders(Code.HTTP_OK, fd.fileSize);

        os = exchange.getResponseBody();

        fis = new FileInputStream(fd.filePath);

        byte[] buffer = new byte[4 * 1024];
        int n;
        int count = 0;

        while ((n = fis.read(buffer, 0, buffer.length)) != -1) {
            os.write(buffer, 0, n);
            upload.addBytesSent(n);

            if (upload.isCanceled()) {
                try {
                    throw new IOException("Upload cancelled");
                } finally {
                    os.close();
                }
            }

            count += n;
            if (count > 4096) {
                count = 0;
                Thread.yield();
            }
        }

    } catch (IOException e) {
        LOG.log(Level.INFO, "Error uploading file type=" + type + ", id=" + id);
        throw e;
    } finally {
        close(os);
        close(fis);

        try {
            exchange.close();
        } catch (Throwable e) {
            // ignore
        }

        if (upload != null) {
            upload.complete();
        }
    }
}

From source file:org.apache.zeppelin.notebook.NotebookTest.java

@Test
public void testSelectingReplImplementation() throws IOException {
    Note note = notebook.createNote();//from w  w  w.ja  v a2  s  .c o m
    note.getNoteReplLoader().setInterpreters(factory.getDefaultInterpreterSettingList());

    // run with defatul repl
    Paragraph p1 = note.addParagraph();
    p1.setText("hello world");
    note.run(p1.getId());
    while (p1.isTerminated() == false || p1.getResult() == null)
        Thread.yield();
    assertEquals("repl1: hello world", p1.getResult().message());

    // run with specific repl
    Paragraph p2 = note.addParagraph();
    p2.setText("%mock2 hello world");
    note.run(p2.getId());
    while (p2.isTerminated() == false || p2.getResult() == null)
        Thread.yield();
    assertEquals("repl2: hello world", p2.getResult().message());
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Deprecated
public boolean deleteFolder(File f, boolean repeat, int period, int timeout) {
    long t = System.currentTimeMillis();
    if (repeat) {
        for (int i = 1; f.isDirectory() && (System.currentTimeMillis() - t) < timeout; i++) {
            l.trace("Cleaning temp folder attempt " + i);
            try {
                Utils.cleanupDir();/*from w ww.  j  a va  2 s .c o  m*/
                l.trace("OK");
                return true;
            } catch (IOException e) {
                l.trace("Cleaning failed " + i, e);
                Thread.yield();
                try {
                    Thread.sleep(period);
                } catch (InterruptedException interruptedException) {
                    Thread.yield();
                }
            }
        }
    } else {
        try {
            Utils.cleanupDir();
            l.trace("OK");
            return true;
        } catch (IOException e) {
            l.trace("Cleaning failed", e);
            Thread.yield();
        }
    }
    return false;
}

From source file:org.jboss.as.test.clustering.cluster.web.passivation.SessionPassivationTestCase.java

@Test
@InSequence(1)/*from   w  w  w.j a  v a  2 s .c  om*/
public void test(
        @ArquillianResource(SessionOperationServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1)
        throws IOException, URISyntaxException {
    DefaultHttpClient client1 = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();
    DefaultHttpClient client2 = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();
    String session1 = null;
    String session2 = null;
    try {
        // This should not trigger any passivation/activation events
        HttpResponse response = client1
                .execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a", "1")));
        try {
            Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
            Assert.assertFalse(response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS));
            session1 = response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        long now = System.currentTimeMillis();
        long start = now;
        boolean passivated = false;

        while (!passivated && ((now - start) < MAX_PASSIVATION_WAIT)) {
            // This will trigger passivation of session1
            response = client2.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a", "2")));
            try {
                checkResponseForHeader(response, SessionOperationServlet.SESSION_ID);
                Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
                passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
                session2 = response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue();
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
            Thread.yield();
            now = System.currentTimeMillis();
        }

        Assert.assertTrue(passivated);
        Assert.assertEquals(session1,
                response.getFirstHeader(SessionOperationServlet.PASSIVATED_SESSIONS).getValue());

        now = System.currentTimeMillis();
        start = now;
        passivated = false;

        // This should trigger activation of session1 and passivation of session2
        response = client1.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
        try {
            checkResponseForHeader(response, SessionOperationServlet.RESULT);
            Assert.assertEquals("1", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
            checkResponseForHeader(response, SessionOperationServlet.ACTIVATED_SESSIONS);
            passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            Assert.assertEquals(session1,
                    response.getFirstHeader(SessionOperationServlet.ACTIVATED_SESSIONS).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Verify session2 was passivated
        while (!passivated && ((now - start) < MAX_PASSIVATION_WAIT)) {
            response = client1.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
            try {
                checkResponseForHeader(response, SessionOperationServlet.RESULT);
                Assert.assertEquals("1", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
                Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
                passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
            Thread.yield();
            now = System.currentTimeMillis();
        }

        Assert.assertTrue(passivated);
        Assert.assertEquals(session2,
                response.getFirstHeader(SessionOperationServlet.PASSIVATED_SESSIONS).getValue());

        now = System.currentTimeMillis();
        start = now;
        passivated = false;

        // This should trigger activation of session2 and passivation of session1
        response = client2.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
        try {
            checkResponseForHeader(response, SessionOperationServlet.RESULT);
            Assert.assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
            checkResponseForHeader(response, SessionOperationServlet.ACTIVATED_SESSIONS);
            passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            Assert.assertEquals(session2,
                    response.getFirstHeader(SessionOperationServlet.ACTIVATED_SESSIONS).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Verify session1 was passivated
        while (!passivated && ((now - start) < MAX_PASSIVATION_WAIT)) {
            response = client2.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
            try {
                checkResponseForHeader(response, SessionOperationServlet.RESULT);
                Assert.assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
                Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
                passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
            Thread.yield();
            now = System.currentTimeMillis();
        }

        Assert.assertTrue(passivated);
        Assert.assertEquals(session1,
                response.getFirstHeader(SessionOperationServlet.PASSIVATED_SESSIONS).getValue());
    } finally {
        HttpClientUtils.closeQuietly(client1);
        HttpClientUtils.closeQuietly(client2);
    }
}

From source file:com.inbravo.scribe.rest.service.crm.cache.CRMSessionCache.java

public final void initialize() {
    if (cacheManager != null) {
        cacheManager.cancel();/*from w w w .j  av a 2s  .  co  m*/
    }
    cacheManager = new Timer(true);
    cacheManager.schedule(new TimerTask() {
        public void run() {
            long now = System.currentTimeMillis();
            try {
                MapIterator itr = cacheMap.mapIterator();
                while (itr.hasNext()) {
                    Object key = itr.next();
                    final CachedObject cobj = (CachedObject) itr.getValue();
                    if (cobj == null || cobj.hasExpired(now)) {

                        if (logger.isDebugEnabled()) {
                            logger.debug("----Inside CRMSessionCache: removing " + key + ": Idle time= "
                                    + (now - cobj.timeAccessedLast) + "; Stale time= " + (now - cobj.timeCached)
                                    + "; Object count in cache= " + cacheMap.size());
                        }
                        itr.remove();
                        Thread.yield();
                    }
                }
            } catch (ConcurrentModificationException cme) {
                /*
                 * This is just a timer cleaning up. It will catch up on cleaning next time it runs.
                 */
                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside CRMSessionCache:Ignorable ConcurrentModificationException");
                }
            }
        }
    }, 0, tiv);
}

From source file:de.uni_rostock.goodod.owl.OntologyCache.java

public FutureTask<OWLOntology> getOntologyAtURI(URI theURI) throws OWLOntologyCreationException {
    int waitCount = 0;
    while (pendingFutures.get() > threadCount) {
        if (0 == ++waitCount % 8) {

            /* /*w w w  .j  a  v  a2s .  c  o  m*/
             * Thight loop a few times, then yield in order to let
             * the other threads finish.
             */
            Thread.yield();
        }
    }
    return getOntologyFutureAtURI(theURI);
}

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

private List<Object> ponderUntilMessageCountReceived(final int expectedCount, final FunctionalTestComponent ftc)
        throws InterruptedException {
    final List<Object> results = new ArrayList<Object>();

    while (ftc.getReceivedMessagesCount() < expectedCount) {
        Thread.yield();
        Thread.sleep(100L);/*from  www.  jav a2 s.c  o m*/
    }

    for (int i = 0; i < ftc.getReceivedMessagesCount(); i++) {
        results.add(ftc.getReceivedMessage(1 + i));
    }
    return results;
}

From source file:ProcessWatcher.java

public int waitfor() {
    while (!stopped) {
        Thread.yield();
    }
    return result;
}