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.apache.hadoop.hbase.rest.TestGetAndPutResource.java

@Test
public void testMultiColumnGetXML() throws Exception {
    String path = "/" + TABLE + "/fakerow";
    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)));
    rowModel.addCell(new CellModel(Bytes.toBytes(COLUMN_3), Bytes.toBytes(VALUE_2)));
    cellSetModel.addRow(rowModel);/*www.j a  v a2  s . co  m*/
    StringWriter writer = new StringWriter();
    xmlMarshaller.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);

    // Try getting all the column values at once.
    path = "/" + TABLE + "/" + ROW_1 + "/" + COLUMN_1 + "," + COLUMN_2 + "," + COLUMN_3;
    response = client.get(path, Constants.MIMETYPE_XML);
    assertEquals(200, response.getCode());
    CellSetModel cellSet = (CellSetModel) xmlUnmarshaller
            .unmarshal(new ByteArrayInputStream(response.getBody()));
    assertTrue(cellSet.getRows().size() == 1);
    assertTrue(cellSet.getRows().get(0).getCells().size() == 3);
    List<CellModel> cells = cellSet.getRows().get(0).getCells();

    assertTrue(containsCellModel(cells, COLUMN_1, VALUE_1));
    assertTrue(containsCellModel(cells, COLUMN_2, VALUE_2));
    assertTrue(containsCellModel(cells, COLUMN_3, VALUE_2));
    response = deleteRow(TABLE, ROW_1);
    assertEquals(response.getCode(), 200);
}

From source file:org.callimachusproject.management.CalliServer.java

protected void submit(final Callable<Void> task) throws Exception {
    checkForErrors();//w ww  . j a v a2  s . c o  m
    executor.submit(new Runnable() {
        public void run() {
            begin();
            try {
                task.call();
            } catch (Exception exc) {
                saveError(exc);
            } finally {
                end();
            }
        }
    });
    Thread.yield();
}

From source file:edu.illinois.enforcemop.examples.jbosscache.PessimisticSyncReplTxTest.java

public void testPut() throws Exception {
    final CacheSPI<Object, Object> c1 = this.cache1;

    Thread t1 = new Thread() {
        public void run() {
            try {
                lock.acquire();/*from   w  w  w  .j  a va2s.c  om*/
                c1.put("/a/b/c", "age", 38);

                lock.release();
                Thread.sleep(300);
                Thread.yield();

                lock.acquire();
                c1.put("/a/b/c", "age", 39);

                lock.release();
                assertEquals(39, c1.get("/a/b/c", "age"));
            } catch (Throwable ex) {
                ex.printStackTrace();
                t1_ex = ex;
            } finally {
                lock.release();
            }
        }
    };

    Thread t2 = new Thread() {
        public void run() {
            try {
                Thread.sleep(100);
                Thread.yield();
                lock.acquire();
                // Should replicate the value right away.
                Integer val = (Integer) cache2.get("/a/b/c", "age");
                assertEquals(new Integer(38), val);
                lock.release();
                Thread.sleep(300);
                Thread.yield();
                Thread.sleep(500);
                lock.acquire();
                val = (Integer) cache2.get("/a/b/c", "age");
                lock.release();
                assertEquals(new Integer(39), val);
            } catch (Throwable ex) {
                ex.printStackTrace();
                t2_ex = ex;
            } finally {
                lock.release();
            }
        }
    };

    // Let the game start
    t1.start();
    t2.start();

    // Wait for thread to die but put an insurance of 5 seconds on it.
    t1.join();
    t2.join();
    if (t1_ex != null) {
        fail("Thread1 failed: " + t1_ex);
    }
    if (t2_ex != null) {
        fail("Thread2 failed: " + t2_ex);
    }
}

From source file:br.com.carlosrafaelgn.fplay.list.RadioStationList.java

public void fetchIcecast(Context context, String genre, String searchTerm) {
    while (!readyToFetch)
        Thread.yield();
    cancel();/*w  w w  . j av  a2 s  .c o m*/
    clear();
    loadingProcessChanged(true);
    final Thread t = new Thread(this, "Icecast Station Fetcher Thread");
    isSavingFavorites = false;
    genreToFetch = genre;
    searchTermToFetch = searchTerm;
    this.context = context;
    readyToFetch = false;
    try {
        t.start();
    } catch (Throwable ex) {
        readyToFetch = true;
        loadingProcessChanged(false);
    }
}

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

@Test
public void testSuffixGlobbingXMLWithNewScanner() 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 ww 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();
    xmlMarshaller.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
    StringBuilder query = new StringBuilder();
    query.append('/');
    query.append(TABLE);
    query.append('/');
    query.append("testrow*");
    response = client.get(query.toString(), Constants.MIMETYPE_XML);
    assertEquals(response.getCode(), 200);
    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
    CellSetModel cellSet = (CellSetModel) xmlUnmarshaller
            .unmarshal(new ByteArrayInputStream(response.getBody()));
    assertTrue(cellSet.getRows().size() == 2);

    response = deleteRow(TABLE, ROW_1);
    assertEquals(response.getCode(), 200);
    response = deleteRow(TABLE, ROW_2);
    assertEquals(response.getCode(), 200);
}

From source file:br.com.carlosrafaelgn.fplay.list.RadioStationList.java

public void fetchFavorites(Context context) {
    while (!readyToFetch)
        Thread.yield();
    cancel();//  w  w w . ja  v a  2 s  . co  m
    clear();
    loadingProcessChanged(true);
    final Thread t = new Thread(this, "Icecast Favorite Stations Fetcher Thread");
    isSavingFavorites = false;
    genreToFetch = null;
    searchTermToFetch = null;
    this.context = context;
    readyToFetch = false;
    try {
        t.start();
    } catch (Throwable ex) {
        readyToFetch = true;
        loadingProcessChanged(false);
    }
}

From source file:com.jcraft.weirdx.Client.java

private static final void reqGrabServer(Client c) throws IOException {
    synchronized (LOCK) {
        for (int i = 1; i < clients.length; i++) {
            if (i == c.index)
                continue;
            if (clients[i] == null)
                continue;
            if (!clients[i].isAlive())
                continue;
            clients[i].serverisgrabed = true;
        }/*ww  w. j  a va2  s  . co m*/
    }
    int i = 0;
    int ii = 100;
    while (true) {
        try {
            Thread.yield();
        } catch (Exception e) {
        }
        for (i = 1; i < clients.length; i++) {
            if (i == c.index || clients[i] == null || !clients[i].isAlive() || clients[i].waitforreq
                    || clients[i].suspended)
                continue;
            //   System.out.println("wait for: "+i);
            i = 0;
            break;
        }
        if (i != 0)
            break;
        ii--;
        if (ii == 0) {
            //   System.out.println("give up..: "+i);
            break;
        }
    }
}

From source file:br.com.carlosrafaelgn.fplay.list.RadioStationList.java

public void saveFavorites(Context context) {
    while (!readyToFetch)
        Thread.yield();
    synchronized (favoritesSync) {
        if (!favoritesLoaded || !favoritesChanged)
            return;
    }//from  w  w w  .  j  a  va2 s . co m
    final Thread t = new Thread(this, "Icecast Favorite Stations Storer Thread");
    isSavingFavorites = true;
    genreToFetch = null;
    searchTermToFetch = null;
    this.context = context;
    readyToFetch = false;
    try {
        t.start();
    } catch (Throwable ex) {
        readyToFetch = true;
    }
}

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

@Test
public void testSuffixGlobbingXML() 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 ww.j  av a  2s .  co  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();
    xmlMarshaller.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
    StringBuilder query = new StringBuilder();
    query.append('/');
    query.append(TABLE);
    query.append('/');
    query.append("testrow*");
    query.append('/');
    query.append(COLUMN_1);
    response = client.get(query.toString(), Constants.MIMETYPE_XML);
    assertEquals(response.getCode(), 200);
    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
    CellSetModel cellSet = (CellSetModel) xmlUnmarshaller
            .unmarshal(new ByteArrayInputStream(response.getBody()));
    List<RowModel> rows = cellSet.getRows();
    assertTrue(rows.size() == 2);
    for (RowModel row : rows) {
        assertTrue(row.getCells().size() == 1);
        assertEquals(COLUMN_1, Bytes.toString(row.getCells().get(0).getColumn()));
    }
    response = deleteRow(TABLE, ROW_1);
    assertEquals(response.getCode(), 200);
    response = deleteRow(TABLE, ROW_2);
    assertEquals(response.getCode(), 200);
}

From source file:com.ubuntuone.android.files.service.MetaService.java

/**
 * Given parents resource path and {@link ArrayList} of {@link NodeInfo}s of
 * its children, syncs cached info of these children. Updating children in
 * one method enables us to make use of database transaction.<br />
 * <ul>/*  w w  w .ja  v  a2  s  . c  o m*/
 * <li>- inserts if child is new</li>
 * <li>- updates if child has changed [thus marks is_cached = false]</li>
 * <li>- deletes if child is missing [dead node]</li>
 * </ul>
 * 
 * @param parentResourcePath
 *            the resource path of childrens parent
 * @param children
 *            {@link NodeInfo}s of the parents children
 * @throws OperationApplicationException 
 * @throws RemoteException 
 */
public void getDirectoryNode(final String resourcePath, final ResultReceiver receiver) {
    Log.i(TAG, "getDirectoryNode()");
    final String[] projection = new String[] { Nodes._ID, Nodes.NODE_RESOURCE_PATH, Nodes.NODE_GENERATION,
            Nodes.NODE_DATA };
    final String selection = Nodes.NODE_RESOURCE_PATH + "=?";

    final Set<Integer> childrenIds = MetaUtilities.getChildrenIds(resourcePath);

    final ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    final Bundle data = new Bundle();
    data.putString(EXTRA_RESOURCE_PATH, resourcePath);

    api.listDirectory(resourcePath, new U1NodeListener() {
        @Override
        public void onStart() {
            if (receiver != null)
                receiver.send(Status.RUNNING, data);
        }

        @Override
        public void onSuccess(U1Node node) {
            if (node.getKind() == U1NodeKind.FILE && ((U1File) node).getSize() == null) {
                // Ignore files with null size.
                return;
            }
            final String[] selectionArgs = new String[] { node.getResourcePath() };
            final Cursor c = contentResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs,
                    null);
            try {
                ContentValues values = Nodes.valuesFromRepr(node);
                if (c.moveToFirst()) {
                    final int id = c.getInt(c.getColumnIndex(Nodes._ID));
                    // Node is live.
                    childrenIds.remove(id);

                    // Update node.
                    final long generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION));
                    final long newGeneration = node.getGeneration();
                    if (generation < newGeneration) {
                        Log.v(TAG, "updating child node, new generation");
                        values.put(Nodes.NODE_IS_CACHED, false);
                        values.put(Nodes.NODE_DATA, "");

                        String data = c.getString(c.getColumnIndex(Nodes.NODE_DATA));
                        FileUtilities.removeSilently(data);

                        Uri uri = MetaUtilities.buildNodeUri(id);
                        ContentProviderOperation op = ContentProviderOperation.newUpdate(uri).withValues(values)
                                .build();
                        operations.add(op);
                        if (operations.size() > 10) {
                            try {
                                contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                                operations.clear();
                            } catch (RemoteException e) {
                                Log.e(TAG, "Remote exception", e);
                            } catch (OperationApplicationException e) {
                                MetaUtilities.setIsCached(resourcePath, false);
                                return;
                            }
                            Thread.yield();
                        }
                    } else {
                        Log.v(TAG, "child up to date");
                    }
                } else {
                    // Insert node.
                    Log.v(TAG, "inserting child");
                    ContentProviderOperation op = ContentProviderOperation.newInsert(Nodes.CONTENT_URI)
                            .withValues(values).build();
                    operations.add(op);
                    if (operations.size() > 10) {
                        try {
                            contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                            operations.clear();
                        } catch (RemoteException e) {
                            Log.e(TAG, "Remote exception", e);
                        } catch (OperationApplicationException e) {
                            MetaUtilities.setIsCached(resourcePath, false);
                            return;
                        }
                        Thread.yield();
                    }
                }
            } finally {
                c.close();
            }
        }

        @Override
        public void onUbuntuOneFailure(U1Failure failure) {
            MetaService.this.onUbuntuOneFailure(failure, receiver);
        }

        @Override
        public void onFailure(U1Failure failure) {
            MetaService.this.onFailure(failure, receiver);
        }

        @Override
        public void onFinish() {
            if (receiver != null)
                receiver.send(Status.FINISHED, data);
        }
    });

    // Remove nodes, which ids are left in childrenIds set.
    if (!childrenIds.isEmpty()) {
        Log.v(TAG, "childrenIDs not empty: " + childrenIds.size());
        final Iterator<Integer> it = childrenIds.iterator();
        while (it.hasNext()) {
            int id = it.next();
            Uri uri = MetaUtilities.buildNodeUri(id);
            ContentProviderOperation op = ContentProviderOperation.newDelete(uri).build();
            operations.add(op);
        }
    } else {
        Log.v(TAG, "childrenIDs empty");
    }

    try {
        long then = System.currentTimeMillis();
        contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
        MetaUtilities.setIsCached(resourcePath, true);
        long now = System.currentTimeMillis();
        Log.d(TAG, "time to update children: " + (now - then));
        contentResolver.notifyChange(Nodes.CONTENT_URI, null);
    } catch (RemoteException e) {
        Log.e(TAG, "", e);
    } catch (OperationApplicationException e) {
        MetaUtilities.setIsCached(resourcePath, false);
        return;
    }
}