List of usage examples for java.lang Thread yield
public static native void yield();
From source file:MyZone.Settings.java
public byte[] readXML(String filename) { byte[] readIn = null; FileChannel channel = null;/* ww w. j a va2 s . c om*/ FileLock lock = null; FileInputStream fis = null; ByteArrayOutputStream baos = null; try { File file = new File(filename); if (!file.exists()) { return null; } fis = new FileInputStream(file); channel = fis.getChannel(); while ((lock = channel.tryLock(0L, Long.MAX_VALUE, true)) == null) { Thread.yield(); } baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; ByteBuffer buf = ByteBuffer.wrap(b); int count = 0; long fileLength = file.length(); while (fileLength > 0) { count = channel.read(buf); if (count >= 0) { fileLength -= count; baos.write(b, 0, count); buf.rewind(); } } readIn = baos.toByteArray(); } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } readIn = null; } finally { try { if (lock != null) { lock.release(); } if (channel != null) { channel.close(); } if (fis != null) { fis.close(); } if (baos != null) { baos.close(); } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } readIn = null; } } return readIn; }
From source file:org.apache.hadoop.hbase.rest.TestGetAndPutResource.java
@Test public void testMultiCellGetPutPB() throws IOException { 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);// www. j a v a 2 s .com 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); Response response = client.put(path, Constants.MIMETYPE_PROTOBUF, cellSetModel.createProtobufOutput()); Thread.yield(); // make sure the fake row was not actually created response = client.get(path, Constants.MIMETYPE_PROTOBUF); assertEquals(response.getCode(), 404); // check that all of the values were created checkValuePB(TABLE, ROW_1, COLUMN_1, VALUE_1); checkValuePB(TABLE, ROW_1, COLUMN_2, VALUE_2); checkValuePB(TABLE, ROW_2, COLUMN_1, VALUE_3); checkValuePB(TABLE, ROW_2, COLUMN_2, VALUE_4); response = deleteRow(TABLE, ROW_1); assertEquals(response.getCode(), 200); response = deleteRow(TABLE, ROW_2); assertEquals(response.getCode(), 200); }
From source file:com.nttec.everychan.chans.dvach.DvachModule.java
private void cssTest(String boardName, final CancellableTask task) throws Exception { /* =*.*= */ class CSSCodeHolder { private volatile String cssCode = null; public synchronized void setCode(String code) { Logger.d(TAG, "set CSS code: " + code); if (cssCode == null) cssCode = code;//from w w w . j a v a 2s .c o m } public boolean isSet() { return cssCode != null; } public String getCode() { return cssCode; } } class WebViewHolder { private WebView webView = null; } final CSSCodeHolder holder = new CSSCodeHolder(); final WebViewHolder wv = new WebViewHolder(); final String cssTest = HttpStreamer.getInstance().getStringFromUrl( getUsingUrl() + boardName + "/csstest.foo", HttpRequestModel.DEFAULT_GET, httpClient, null, task, false); long startTime = System.currentTimeMillis(); Async.runOnUiThread(new Runnable() { @Override public void run() { wv.webView = new WebView(MainApplication.getInstance()); wv.webView.setWebViewClient(new WebViewClient() { @Override public void onLoadResource(WebView view, String url) { if (url.contains("?code=") && !task.isCancelled()) { holder.setCode(url.substring(url.indexOf("?code=") + 6)); } } }); wv.webView.loadDataWithBaseURL("http://127.0.0.1/csstest.foo", cssTest, "text/html", "UTF-8", ""); } }); while (!holder.isSet()) { long time = System.currentTimeMillis() - startTime; if ((task != null && task.isCancelled()) || time > 5000) break; Thread.yield(); } Async.runOnUiThread(new Runnable() { @Override public void run() { try { wv.webView.stopLoading(); wv.webView.clearCache(true); wv.webView.destroy(); } catch (Exception e) { Logger.e(TAG, e); } } }); if (task != null && task.isCancelled()) throw new InterruptedException("interrupted"); String cssCode = holder.getCode(); if (cssCode != null) { HttpStreamer.getInstance().getBytesFromUrl(getUsingUrl() + boardName + "/csstest.foo?code=" + cssCode, HttpRequestModel.DEFAULT_GET, httpClient, null, task, false); } }
From source file:org.apache.hadoop.hbase.rest.TestGetAndPutResource.java
@Test public void testMetrics() throws IOException, JAXBException { final String path = "/" + TABLE + "/" + ROW_4 + "/" + COLUMN_1; Response response = client.put(path, Constants.MIMETYPE_BINARY, Bytes.toBytes(VALUE_4)); assertEquals(response.getCode(), 200); Thread.yield(); response = client.get(path, Constants.MIMETYPE_JSON); assertEquals(response.getCode(), 200); assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type")); response = deleteRow(TABLE, ROW_4);/* w w w.j ava 2 s . c o m*/ assertEquals(response.getCode(), 200); UserGroupInformation ugi = User.getCurrent().getUGI(); METRICS_ASSERT.assertCounterGt("requests", 2l, RESTServlet.getInstance(conf, ugi).getMetrics().getSource()); METRICS_ASSERT.assertCounterGt("successfulGet", 0l, RESTServlet.getInstance(conf, ugi).getMetrics().getSource()); METRICS_ASSERT.assertCounterGt("successfulPut", 0l, RESTServlet.getInstance(conf, ugi).getMetrics().getSource()); METRICS_ASSERT.assertCounterGt("successfulDelete", 0l, RESTServlet.getInstance(conf, ugi).getMetrics().getSource()); }
From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransactionTest.java
@Test public void testTransactionAtomicity() throws Exception { // This test runs multiple transactions in parallel, with KeyValueService.put calls throwing // a RuntimeException from time to time and hanging other times. which effectively kills the // thread. We ensure that every transaction either adds 5 rows to the table or adds 0 rows // by checking at the end that the number of rows is a multiple of 5. final String tableName = "table"; Random random = new Random(1); final UnstableKeyValueService unstableKvs = new UnstableKeyValueService(keyValueService, random); final TestTransactionManager unstableTransactionManager = new TestTransactionManagerImpl(unstableKvs, timestampService, lockClient, lockService, transactionService, conflictDetectionManager, sweepStrategyManager);// w ww .java2 s . c om ScheduledExecutorService service = PTExecutors.newScheduledThreadPool(20); for (int i = 0; i < 30; i++) { final int threadNumber = i; service.schedule(new Callable<Void>() { @Override public Void call() throws Exception { if (threadNumber == 10) { unstableKvs.setRandomlyThrow(true); } if (threadNumber == 20) { unstableKvs.setRandomlyHang(true); } Transaction transaction = unstableTransactionManager.createNewTransaction(); BatchingVisitable<RowResult<byte[]>> results = transaction.getRange(tableName, RangeRequest.builder().build()); final MutableInt nextIndex = new MutableInt(0); results.batchAccept(1, AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() { @Override public boolean visit(RowResult<byte[]> row) throws Exception { byte[] dataBytes = row.getColumns().get("data".getBytes()); BigInteger dataValue = new BigInteger(dataBytes); nextIndex.setValue(Math.max(nextIndex.toInteger(), dataValue.intValue() + 1)); return true; } })); // nextIndex now contains the least row number not already in the table. Add 5 more // rows to the table. for (int j = 0; j < 5; j++) { int rowNumber = nextIndex.toInteger() + j; Cell cell = Cell.create(("row" + rowNumber).getBytes(), "data".getBytes()); transaction.put(tableName, ImmutableMap.of(cell, BigInteger.valueOf(rowNumber).toByteArray())); Thread.yield(); } transaction.commit(); return null; } }, i * 20, TimeUnit.MILLISECONDS); } service.shutdown(); service.awaitTermination(1, TimeUnit.SECONDS); // Verify each table has a number of rows that's a multiple of 5 Transaction verifyTransaction = txManager.createNewTransaction(); BatchingVisitable<RowResult<byte[]>> results = verifyTransaction.getRange(tableName, RangeRequest.builder().build()); final MutableInt numRows = new MutableInt(0); results.batchAccept(1, AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() { @Override public boolean visit(RowResult<byte[]> row) throws Exception { numRows.increment(); return true; } })); Assert.assertEquals(0, numRows.toInteger() % 5); }
From source file:ac.core.ConfigLoader.java
/** * showConfigNodes(...) method is used to recursively scan the XML config * file and display the nodes in tree format. * * @param parent/* w w w . j a v a 2s . c om*/ * @param level level of the node, increased for each child-node to allow * tabbed tree display output * */ protected void showConfigNodes(org.w3c.dom.Node parent, int level) { // create a local class to display node value/text and associated // node attributes class SubShowNode { // loop through the node attributes for the node passed String displayNodeAttributes(org.w3c.dom.Node node) { // create string build object to support string concatanation StringBuilder sb = new StringBuilder(); // retrieve node attributes (if any) ArrayList nAttributes = _xmlr.getNodeAttributes(node); // loop through the attributes array and append them to the // string builder object for (Object na : nAttributes) { // append the attribute details (key/text) to the string // builder object sb.append(" [ATTR=").append(((org.w3c.dom.Node) na).getNodeName()).append("//") .append(((org.w3c.dom.Node) na).getNodeValue()).append("]"); // yield processing to other threads Thread.yield(); } // return the string builder representation as a string return sb.toString(); } } // declare the showNode class to allow methods to reference the display // method to prevent duplicaion in code SubShowNode showNode = new SubShowNode(); // retrieve the child nodes for processing ArrayList nodes = _xmlr.getNodeChildren(parent); // if node level is 1, then this is root node, display it with no // indentation if (level == 1) { // display the parent node name String data = StringUtils.repeat('~', level) + parent.getNodeName(); // use the sub function to extract node attributes data += showNode.displayNodeAttributes(parent); // display all collected data to the user output System.out.println(data); } // parse the list of child nodes for the node being processed for (Object node : nodes) { // display the parent node name String data = StringUtils.repeat('\t', level) + ((org.w3c.dom.Node) node).getNodeName(); // use the sub function to extract node attributes data += showNode.displayNodeAttributes((org.w3c.dom.Node) node); // if node has a text value, display the text if (_xmlr.getNodeText((org.w3c.dom.Node) node) != null) { data += " (TEXT=" + _xmlr.getNodeText((org.w3c.dom.Node) node) + ")"; } // display all collected data to the user output System.out.println(data); // recall the function (recursion) to see if the node has child // nodes and preocess them in hierarchial level showConfigNodes((org.w3c.dom.Node) node, (level + 1)); // yield processing to other threads Thread.yield(); } }
From source file:com.alibaba.otter.node.etl.select.selector.canal.CanalEmbedSelector.java
private void applyWait(int emptyTimes) { int newEmptyTimes = emptyTimes > maxEmptyTimes ? maxEmptyTimes : emptyTimes; if (emptyTimes <= 3) { // 3 Thread.yield(); } else { // 3?sleep 10ms LockSupport.parkNanos(1000 * 1000L * newEmptyTimes); }/*from ww w . jav a 2 s . com*/ }
From source file:org.apache.cassandra.Util.java
public static void spinAssertEquals(Object expected, Supplier<Object> s, int timeoutInSeconds) { long now = System.currentTimeMillis(); while (System.currentTimeMillis() - now < now + (1000 * timeoutInSeconds)) { if (s.get().equals(expected)) break; Thread.yield(); }//from w w w . j av a2 s . c om assertEquals(expected, s.get()); }
From source file:com.apporiented.hermesftp.client.FtpTestClient.java
private void executeSend(RawSender l) { Thread t = new Thread(l); t.start(); while (t.isAlive()) { Thread.yield(); } }
From source file:org.apache.hadoop.hbase.rest.RowResourceBase.java
protected static Response deleteValue(String table, String row, String column) throws IOException { StringBuilder path = new StringBuilder(); path.append('/'); path.append(table);/*www .jav a 2 s . co m*/ path.append('/'); path.append(row); path.append('/'); path.append(column); Response response = client.delete(path.toString()); Thread.yield(); return response; }