List of usage examples for java.lang Thread yield
public static native void yield();
From source file:com.esminis.server.mariadb.server.MariaDbServerLauncher.java
void initializeDataDirectory(Context context, File binary, File root) throws IOException { File[] files = root.listFiles(); if (files != null && files.length > 0) { return;//from w w w. j a v a 2 s .co m } synchronized (lock) { final List<String> environment = getEnvironment(); final List<String> command = createCommandInternal(context, binary, root); Collections.addAll(command, "--bootstrap", "--log-warnings=0", "--max_allowed_packet=8M", "--net_buffer_length=16K"); final File dataMysqlDirectory = new File(root, "mysql"); if (dataMysqlDirectory.isDirectory()) { return; } if (!dataMysqlDirectory.mkdirs()) { throw new IOException("Cannot create directory: " + dataMysqlDirectory.getAbsolutePath()); } final Process process = Runtime.getRuntime().exec(command.toArray(new String[command.size()]), environment.toArray(new String[environment.size()]), root); final Object[] finishedWithError = { null }; try { final OutputStream stream = process.getOutputStream(); Observable.create(new Observable.OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { final InputStream inputStream = process.getErrorStream(); String data = ""; for (;;) { synchronized (finishedWithError) { if (finishedWithError[0] != null) { break; } } try { int available = inputStream.available(); if (available > 0) { for (int i = 0; i < available; i++) { data += (char) inputStream.read(); } if (getFreeSpace(dataMysqlDirectory) < 1024L * 1024L || data.contains("No space left on device")) { synchronized (finishedWithError) { finishedWithError[0] = new IOException("No space left on device"); } process.destroy(); break; } } } catch (Throwable ignored) { } Thread.yield(); } subscriber.onCompleted(); } }).subscribeOn(Schedulers.newThread()).subscribe(); writeToStream(stream, "use mysql;\n"); writeToStream(stream, context, "sql/mysql_system_tables.sql"); writeToStream(stream, context, "sql/mysql_performance_tables.sql"); writeToStream(stream, context, "sql/mysql_system_tables_data.sql"); writeToStream(stream, context, "sql/add_root_from_any_host.sql"); writeToStream(stream, context, "sql/fill_help_tables.sql"); writeToStream(stream, "exit;\n"); process.waitFor(); } catch (Throwable e) { FileUtils.deleteDirectory(root); //noinspection ResultOfMethodCallIgnored root.mkdirs(); synchronized (finishedWithError) { if (finishedWithError[0] != null && finishedWithError[0] instanceof IOException) { throw (IOException) finishedWithError[0]; } else { throw new IOException( e.toString() + "\n\nLog:\n" + IOUtils.toString(process.getErrorStream())); } } } finally { synchronized (finishedWithError) { if (finishedWithError[0] == null) { finishedWithError[0] = true; } } } } }
From source file:com.callidusrobotics.swing.SwingConsole.java
@SuppressWarnings("PMD.NullAssignment") private char getKeyTyped() { lastKeyTyped = null;/*from w ww .j ava 2 s.c o m*/ while (lastKeyTyped == null) { Thread.yield(); } return lastKeyTyped.getKeyChar(); }
From source file:org.apache.hadoop.hbase.stargate.TestRowResource.java
Response putValueXML(String table, String row, String column, String value) throws IOException, JAXBException { StringBuilder path = new StringBuilder(); path.append('/'); path.append(table);/*from w ww . ja v a2s.c o m*/ path.append('/'); path.append(row); path.append('/'); path.append(column); RowModel rowModel = new RowModel(row); rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value))); CellSetModel cellSetModel = new CellSetModel(); cellSetModel.addRow(rowModel); StringWriter writer = new StringWriter(); marshaller.marshal(cellSetModel, writer); Response response = client.put(path.toString(), MIMETYPE_XML, Bytes.toBytes(writer.toString())); Thread.yield(); return response; }
From source file:nl.b3p.viewer.util.databaseupdate.ScriptRunner.java
/** * Runs an SQL script (read in using the Reader parameter) using the * connection passed in//w w w . j a v a2 s. c o m * * @param conn - the connection to use for the script * @param reader - the source of the script * @throws SQLException if any SQL errors occur * @throws IOException if there is an error reading from the Reader */ private void runScript(Connection conn, Reader reader) throws IOException, SQLException { StringBuffer command = null; try { LineNumberReader lineReader = new LineNumberReader(reader); String line = null; while ((line = lineReader.readLine()) != null) { if (command == null) { command = new StringBuffer(); } String trimmedLine = line.trim(); if (trimmedLine.startsWith("--")) { log.debug(trimmedLine); } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) { // Do nothing } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) { // Do nothing } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) { command.append(line.substring(0, line.lastIndexOf(getDelimiter()))); command.append(" "); Statement statement = conn.createStatement(); log.debug(command); boolean hasResults = false; if (stopOnError) { hasResults = statement.execute(command.toString()); } else { try { statement.execute(command.toString()); } catch (SQLException e) { e.fillInStackTrace(); log.error("Error executing: " + command, e); } } if (autoCommit && !conn.getAutoCommit()) { conn.commit(); } ResultSet rs = statement.getResultSet(); if (hasResults && rs != null) { ResultSetMetaData md = rs.getMetaData(); int cols = md.getColumnCount(); for (int i = 0; i < cols; i++) { String name = md.getColumnLabel(i); log.debug(name + "\t"); } while (rs.next()) { for (int i = 0; i < cols; i++) { String value = rs.getString(i); log.debug(value + "\t"); } } } command = null; try { statement.close(); } catch (Exception e) { // Ignore to workaround a bug in Jakarta DBCP } Thread.yield(); } else { command.append(line); command.append(" "); } } if (!autoCommit) { conn.commit(); } } catch (SQLException e) { e.fillInStackTrace(); log.error("Error executing: " + command, e); throw e; } catch (IOException e) { e.fillInStackTrace(); log.error("Error executing: " + command, e); throw e; } finally { if (!this.autoCommit) { conn.rollback(); } } }
From source file:org.mule.transport.amqp.harness.AmqpTestClient.java
public GetResponse waitUntilGetMessageWithAmqp(String queue, long timeout) throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < timeout) { GetResponse getResponse = getMessageWithAmqp(queue); if (getResponse != null) { return getResponse; }//from ww w . j av a2s . c o m Thread.yield(); Thread.sleep(250L); } return null; }
From source file:org.coltram.nsd.bonjour.BonjourProcessor.java
public void callAction(JSONObject object, String serviceId, final AtomConnection connection, String callBack) throws JSONException { final DiscoveredZCService bonjourService = topManager.getServiceManager().findBonjourService(serviceId); if (bonjourService == null) { log.info("no service with id " + serviceId + " in callAction"); return;// w w w . j a v a2 s. c o m } if (bonjourService.isLocal()) { // find the LocalExposedBonjourService in question LocalExposedBonjourService localcbs = LocalExposedBonjourService.getServiceById(serviceId); // send the info to that service object.put("originAtom", connection.getId()); localcbs.notifyListeners(object.toString()); } else { try { Socket socket = bonjourService.getSocket(); int replyPort = -1; final InetAddress inetAddress = socket.getInetAddress(); if (callBack != null) { // wait for reply on the same socket ServerSocket serverSocket = connection.getServerSocket(); replyPort = serverSocket.getLocalPort(); log.finer("start server for reply " + serverSocket.getLocalPort()); new Thread(new ReplyListener(serverSocket, connection.getConnection())).start(); Thread.yield(); } String ia = inetAddress.toString(); if (ia.startsWith("/")) { ia = ia.substring(1); } object.put("address", LocalHost.name); object.put("replyPort", replyPort + ""); object.put("originAtom", connection.getId()); DataOutputStream dos = bonjourService.getSocketDOS(); dos.writeBytes(object.toString() + "\n"); dos.flush(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.idocbox.flame.Helios.java
/** * fire them!/*w w w. j a v a 2s . c om*/ * @param ds data source. * @param dsSpliter data source spliter. * @param mapper mapper. * @param reducer reducer. * @return */ public Collector<Map<K, V>> fire(JobConfig<K, V, T> jobConfig) { long start = System.currentTimeMillis(); Collector<Map<K, V>> resultCollector = null; // data source. DataSource<T> dataSource = jobConfig.getDataSource(); // data source spliter. DataSourceSpliter<T> dataSourceSpliter = jobConfig.getDataSourceSpliter(); // mapper worker. root mapper worker. MapperWorker<K, V, T> mapperWorker = jobConfig.getMapperWorker(); // reducer worker. root reducer worker. ReducerWorker<K, V> reducerWorker = jobConfig.getReducerWorker(); // mapper. Mapper<K, V, T> mapper = jobConfig.getMapper(); // reducer. Reducer<K, V> reducer = jobConfig.getReducer(); // keeper. Keeper<Collector<Map<K, V>>> keeper = jobConfig.getKeeper(); // spliting phase. //split data source into serveral data source. log.info("spliting datasource ..."); Map<String, DataSource<T>> dsMap = dataSourceSpliter.split(dataSource); long m1 = System.currentTimeMillis(); long cost1 = m1 - start; double seconds1 = cost1 / 1000; log.info("spliting datasource: cost " + seconds1 + " s"); // generate worker for mapper.create() if (null == dsMap || dsMap.isEmpty()) { log.info("Splited data source is empty! exit flame!"); return null; } // mapping phase. // generate mapper worker. log.info("mapping && reducing ..."); Set<String> dsKeys = dsMap.keySet(); //mapper thread size. int mapperThreadSize = dsKeys.size() > jobConfig.getMaxMapperWorker() ? jobConfig.getMaxMapperWorker() : dsKeys.size(); //create mapper worker thread pool. ExecutorService mapperWorkerThreadPool = Executors.newFixedThreadPool(mapperThreadSize); int dataSourceSize = 0; for (String key : dsKeys) { //create mapper worker baby. MapperWorker<K, V, T> mapperWorkerBaby = mapperWorker.create(key); //assign data source and run the worker. DataSource<T> dsUnit = dsMap.get(key); if (null != dsUnit) { //execute mapper work in thread pool. mapperWorkerThreadPool .execute(new MapperWorkerRunable<K, V, T>(mapperWorkerBaby, dsUnit, mapper, keeper)); dataSourceSize++; } } //shutdown executor service. mapperWorkerThreadPool.shutdown(); // reduce phase. //generate reducer worker, assign mapper worker's compute result // to reducer worker. //mapper thread size. //create reducer worker thread pool. ExecutorService reducerWorkerThreadPool = Executors.newFixedThreadPool(jobConfig.getMaxReducerWorker()); //get 2 collector, merge them into one, then passed to reducer. Set<ReducerWorker<K, V>> reducerWorkers = new HashSet<ReducerWorker<K, V>>(); int j = 0; int expectedReducTime = dataSourceSize - 1; while (true) {//reduce while there is more than one element in set. if (mapperWorkerThreadPool.isTerminated()) { int count = keeper.count(); if (count == 0) {//no mapped result. log.info("there is no result given by mapper. exit!"); return null; } } if (j == expectedReducTime) { log.info("complete reduce. exit flame."); break; } Set<Collector<Map<K, V>>> collectors = new HashSet<Collector<Map<K, V>>>(2); collectors.add(keeper.take()); collectors.add(keeper.take()); // get an idle worker. ReducerWorker<K, V> reducerWorkerBaby = chooseIdle(reducerWorkers, reducerWorker); log.info("reducing, collector size = " + keeper.size()); reducerWorkerThreadPool .execute(new ReducerWorkerRunnable<K, V>(reducerWorkerBaby, collectors, reducer, keeper)); j++; } //shutdown reducer worker thread pool. reducerWorkerThreadPool.shutdown(); // collect result phase. while (!reducerWorkerThreadPool.isTerminated()) { Thread.yield(); } if (null != keeper && keeper.size() == 1) { resultCollector = keeper.poll(); } else {// error occured. int size = 0; if (null != keeper) { size = keeper.size(); } log.info("after reduce, the result collector is not expected! collector size is " + size); } //return result collector. long end = System.currentTimeMillis(); long cost = end - m1; double seconds = cost / 1000; log.info("mapping & reducing: cost " + seconds + " s"); return resultCollector; }
From source file:com.indeed.lsmtree.recordlog.TestRecordLogDirectory.java
public void testRandomWithReader() 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 . jav a2 s .c om public void run() { try { final Random r = new Random(index); for (int i = 0; i < 10000; i++) { int rand = r.nextInt(positions.size()); final RecordFile.Reader<String> reader = fileCache.reader(positions.get(rand)); assertTrue(reader.next()); assertEquals(reader.get(), strings.get(rand)); reader.close(); } } catch (IOException e) { throw new RuntimeException(e); } finally { done.decrementAndGet(); } } }).start(); } while (done.get() > 0) { Thread.yield(); } fileCache.close(); }
From source file:org.cobbzilla.util.mq.kestrel.KestrelBasicIT.java
private void awaitCommand(ControllableConsumer consumer, ControllableConsumer.Command command) throws InterruptedException { consumer.addCommand(command);//from w w w. j av a2 s . c om while (consumer.getMostRecentCommand() != command) { synchronized (consumer.lock) { consumer.lock.wait(WAIT_TIME); } Thread.yield(); } }
From source file:nya.miku.wishmaster.http.recaptcha.RecaptchaAjax.java
private static String getChallengeInternal(final String address, final String data, CancellableTask task, final HttpHost proxy) throws Exception { Logger.d(TAG, "not intercepting; proxy: " + (proxy == null ? "disabled" : "enabled")); if (proxy != null) { Logger.d(TAG, "AJAX recaptcha not using (proxy and old API)"); throw new Exception("proxy && old API"); //? ? ? ? reflection ???, .. js-antiddos, ? ( noscript ) }//from www . ja v a2s. c o m final Context context = MainApplication.getInstance(); final Holder holder = new Holder(); sHandler.post(new Runnable() { @SuppressLint("SetJavaScriptEnabled") @Override public void run() { holder.webView = new WebView(context); holder.webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onLoadResource(WebView view, String url) { String challenge = getChallengeFromImageUrl(url); if (challenge != null) holder.challenge = challenge; super.onLoadResource(view, url); } }); holder.webView.getSettings().setUserAgentString(CUSTOM_UA); holder.webView.getSettings().setJavaScriptEnabled(true); holder.webView.loadDataWithBaseURL(address, data, "text/html", "UTF-8", null); } }); long startTime = System.currentTimeMillis(); while (holder.challenge == null) { long time = System.currentTimeMillis() - startTime; if ((task != null && task.isCancelled()) || time > TIMEOUT) break; Thread.yield(); } sHandler.post(new Runnable() { @Override public void run() { try { holder.webView.stopLoading(); holder.webView.clearCache(true); holder.webView.destroy(); } catch (Exception e) { Logger.e(TAG, e); } } }); if (holder.challenge == null) throw new RecaptchaException("couldn't get Recaptcha Challenge (AJAX)"); return holder.challenge; }