List of usage examples for java.lang Thread yield
public static native void yield();
From source file:com.dbmojo.QueryExecutor.java
/** Try and grab a connection from the pool. Keep trying until we succeed. * If their is some sort of connection problem, the open() method will throw * an exception and bail//from www .j a v a 2 s.c o m */ private void open(boolean update) throws Exception { if (this.pool != null) { this.conn = pool.checkOut(update); if (this.conn == null) { while (this.conn == null) { Thread.yield(); this.conn = pool.checkOut(update); } } } }
From source file:nya.miku.wishmaster.http.cloudflare.CloudflareUIHandler.java
/** * ?-? Cloudflare./*from ww w . j ava 2s. co m*/ * * @param e ? {@link CloudflareException} * @param chan * @param activity ?, ? ( ? ? ), * ? ? WebView ? Anti DDOS ? javascript. * ??? ? UI ({@link Activity#runOnUiThread(Runnable)}) * @param cfTask ?? * @param callback ? {@link Callback} */ static void handleCloudflare(final CloudflareException e, final HttpChanModule chan, final Activity activity, final CancellableTask cfTask, final InteractiveException.Callback callback) { if (cfTask.isCancelled()) return; if (!e.isRecaptcha()) { // ? anti DDOS if (!CloudflareChecker.getInstance().isAvaibleAntiDDOS()) { //? ? ?? , ? ? ? // ?, ? ChanModule, // ? ? () cloudflare ? ? // ? ? ? ? ? CloudflareChecker while (!CloudflareChecker.getInstance().isAvaibleAntiDDOS()) Thread.yield(); if (!cfTask.isCancelled()) activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onSuccess(); } }); return; } Cookie cfCookie = CloudflareChecker.getInstance().checkAntiDDOS(e, chan.getHttpClient(), cfTask, activity); if (cfCookie != null) { chan.saveCookie(cfCookie); if (!cfTask.isCancelled()) { activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onSuccess(); } }); } } else if (!cfTask.isCancelled()) { activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onError(activity.getString(R.string.error_cloudflare_antiddos)); } }); } } else { // ? final Recaptcha recaptcha; try { recaptcha = CloudflareChecker.getInstance().getRecaptcha(e, chan.getHttpClient(), cfTask); } catch (RecaptchaException recaptchaException) { if (!cfTask.isCancelled()) activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onError(activity.getString(R.string.error_cloudflare_get_captcha)); } }); return; } if (!cfTask.isCancelled()) activity.runOnUiThread(new Runnable() { @SuppressLint("InflateParams") @Override public void run() { Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? new ContextThemeWrapper(activity, R.style.Neutron_Medium) : activity; View view = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_cloudflare_captcha, null); ImageView captchaView = (ImageView) view.findViewById(R.id.dialog_captcha_view); final EditText captchaField = (EditText) view.findViewById(R.id.dialog_captcha_field); captchaView.setImageBitmap(recaptcha.bitmap); DialogInterface.OnClickListener process = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cfTask.isCancelled()) return; PriorityThreadFactory.LOW_PRIORITY_FACTORY.newThread(new Runnable() { @Override public void run() { String answer = captchaField.getText().toString(); Cookie cfCookie = CloudflareChecker.getInstance().checkRecaptcha(e, (ExtendedHttpClient) chan.getHttpClient(), cfTask, recaptcha.challenge, answer); if (cfCookie != null) { chan.saveCookie(cfCookie); if (!cfTask.isCancelled()) { activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onSuccess(); } }); } } else { // (?, , ) handleCloudflare(e, chan, activity, cfTask, callback); } } }).start(); } }; DialogInterface.OnCancelListener onCancel = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { callback.onError(activity.getString(R.string.error_cloudflare_cancelled)); } }; if (cfTask.isCancelled()) return; final AlertDialog recaptchaDialog = new AlertDialog.Builder(dialogContext).setView(view) .setPositiveButton(R.string.dialog_cloudflare_captcha_check, process) .setOnCancelListener(onCancel).create(); recaptchaDialog.getWindow() .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); recaptchaDialog.setCanceledOnTouchOutside(false); recaptchaDialog.show(); captchaView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recaptchaDialog.dismiss(); if (cfTask.isCancelled()) return; PriorityThreadFactory.LOW_PRIORITY_FACTORY.newThread(new Runnable() { @Override public void run() { handleCloudflare(e, chan, activity, cfTask, callback); } }).start(); } }); } }); } }
From source file:eu.flatworld.worldexplorer.layer.nltl7.NLTL7HTTPProvider.java
@Override public void run() { while (true) { while (getQueueSize() != 0) { Tile tile = peekTile();//from w w w.j ava2 s. com synchronized (tile) { String s = String.format(NLTL7Layer.HTTP_BASE, tile.getL(), tile.getX(), tile.getY()); LogX.log(Level.FINER, s); GetMethod gm = new GetMethod(s); gm.setRequestHeader("User-Agent", WorldExplorer.USER_AGENT); try { int response = client.executeMethod(gm); LogX.log(Level.FINEST, NAME + " " + response + " " + s); if (response == HttpStatus.SC_OK) { InputStream is = gm.getResponseBodyAsStream(); BufferedImage bi = ImageIO.read(is); is.close(); if (bi != null) { tile.setImage(bi); } } } catch (Exception ex) { LogX.log(Level.FINER, "", ex); } finally { gm.releaseConnection(); } LogX.log(Level.FINEST, NAME + " dequeueing: " + tile); unqueueTile(tile); } firePropertyChange(P_DATAREADY, null, tile); Thread.yield(); } firePropertyChange(P_IDLE, false, true); try { Thread.sleep(QUEUE_SLEEP_TIME); } catch (Exception ex) { } ; } }
From source file:com.zavakid.mushroom.impl.TestSinkQueue.java
/** * Test blocking when queue is empty/*from ww w. j a v a 2 s.c o m*/ * * @throws Exception */ @Test public void testEmptyBlocking() throws Exception { final SinkQueue<Integer> q = new SinkQueue<Integer>(2); final Runnable trigger = mock(Runnable.class); // try consuming emtpy equeue and blocking Thread t = new Thread() { @Override public void run() { try { assertEquals("element", 1, (int) q.dequeue()); q.consume(new Consumer<Integer>() { public void consume(Integer e) { assertEquals("element", 2, (int) e); trigger.run(); } }); } catch (InterruptedException e) { LOG.warn("Interrupted", e); } } }; t.start(); Thread.yield(); // Let the other block q.enqueue(1); q.enqueue(2); t.join(); verify(trigger).run(); }
From source file:imitationLearning.WordSequenceCache.java
/** * *///from w w w . j a va 2s . c o m @SuppressWarnings("unchecked") public void cleanup() { long now = System.currentTimeMillis(); ArrayList<K> deleteKey = null; synchronized (cacheMap) { MapIterator itr = cacheMap.mapIterator(); deleteKey = new ArrayList<K>((cacheMap.size() / 2) + 1); K key = null; CacheObject c = null; while (itr.hasNext()) { key = (K) itr.next(); c = (CacheObject) itr.getValue(); if (c != null && (now > (timeToLive + c.lastAccessed))) { deleteKey.add(key); } } } for (K key : deleteKey) { synchronized (cacheMap) { cacheMap.remove(key); } Thread.yield(); } }
From source file:org.apache.axis2.transport.mail.MailRequestResponseClient.java
private Message waitForReply(String msgId) throws Exception { Thread.yield(); Thread.sleep(100);//from w ww.j a va 2 s . c o m Message reply = null; boolean replyNotFound = true; int retryCount = 50; while (replyNotFound) { log.debug("Checking for response ... with MessageID : " + msgId); reply = getMessage(msgId); if (reply != null) { replyNotFound = false; } else { if (retryCount-- > 0) { Thread.sleep(100); } else { break; } } } return reply; }
From source file:eu.flatworld.worldexplorer.layer.bmng.BMNGHTTPProvider.java
@Override public void run() { while (true) { while (getQueueSize() != 0) { Tile tile = peekTile();//w w w . ja v a 2 s.c om synchronized (tile) { String s = String.format(BMNGLayer.HTTP_BASE, year, month, tile.getL(), tile.getX(), tile.getY()); LogX.log(Level.FINER, s); GetMethod gm = new GetMethod(s); gm.setRequestHeader("User-Agent", WorldExplorer.USER_AGENT); try { int response = client.executeMethod(gm); LogX.log(Level.FINEST, NAME + " " + response + " " + s); if (response == HttpStatus.SC_OK) { InputStream is = gm.getResponseBodyAsStream(); BufferedImage bi = ImageIO.read(is); is.close(); if (bi != null) { tile.setImage(bi); } } } catch (Exception ex) { LogX.log(Level.FINER, "", ex); } finally { gm.releaseConnection(); } LogX.log(Level.FINEST, NAME + " dequeueing: " + tile); unqueueTile(tile); } firePropertyChange(P_DATAREADY, null, tile); Thread.yield(); } firePropertyChange(P_IDLE, false, true); try { Thread.sleep(QUEUE_SLEEP_TIME); } catch (Exception ex) { } ; } }
From source file:org.ros.android.acm_serial.PollingInputStream.java
@Override public synchronized int read(byte[] buffer, int offset, int length) throws IOException { int bytesRead = 0; if (length > 0) { while (available() == 0) { // Block until there are bytes to read. Thread.yield(); }//from ww w .j av a 2 s.c om synchronized (readBuffer) { bytesRead = Math.min(length, available()); System.arraycopy(readBuffer, readPosition, buffer, offset, bytesRead); readPosition += bytesRead; } } return bytesRead; }
From source file:bigbird.benchmark.HttpBenchmark.java
public void execute() { params = getHttpParams(socketTimeout, useHttp1_0); for (RequestGenerator g : requestGenerators) { g.setParameters(params);// w w w . j av a 2 s .c o m } host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); ThreadPoolExecutor workerPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(r, "ClientPool"); } }); workerPool.prestartAllCoreThreads(); BenchmarkWorker[] workers = new BenchmarkWorker[threads]; for (int i = 0; i < threads; i++) { workers[i] = new BenchmarkWorker(params, verbosity, requestGenerators[i], host, requests, keepAlive); workerPool.execute(workers[i]); } while (workerPool.getCompletedTaskCount() < threads) { Thread.yield(); try { Thread.sleep(1000); } catch (InterruptedException ignore) { } } workerPool.shutdown(); ResultProcessor.printResults(workers, host, url.toString(), contentLength); }
From source file:uk.ac.cam.caret.sakai.rwiki.tool.service.impl.PopulateServiceImpl.java
public void init() throws IOException { ComponentManager cm = org.sakaiproject.component.cover.ComponentManager.getInstance(); renderService = (RenderService) load(cm, RenderService.class.getName()); siteService = (SiteService) load(cm, SiteService.class.getName()); for (Iterator i = seedPages.iterator(); i.hasNext();) { RWikiCurrentObject seed = (RWikiCurrentObject) i.next(); if (seed.getSource().startsWith("bundle:")) { String[] source = seed.getSource().split(":"); ResourceLoader rl = new ResourceLoader(source[1]); seed.setContent(rl.getString(source[2])); } else {//from www. j a v a 2 s . c o m BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { br = new BufferedReader( new InputStreamReader(getClass().getResourceAsStream(seed.getSource()), "UTF-8")); char[] c = new char[2048]; for (int ic = br.read(c); ic >= 0; ic = br.read(c)) { if (ic == 0) Thread.yield(); else sb.append(c, 0, ic); } } finally { br.close(); } seed.setContent(sb.toString()); } } }