List of usage examples for java.lang Thread yield
public static native void yield();
From source file:ac.core.ConfigLoader.java
/** * extractConfigFile(...) method verifies if the external config exists, if * not, it tries to extract the config file from jar file. If either are * unsuccessful, exception is thrown to notify user of missing config. * * @param filename location of the config file * @throws Exception/*from www . j a va2 s .c om*/ */ private void extractConfigFile(String filename) throws Exception { // create a reference to the location of the configuration file File cf = new File(filename); // if the file does not exist, try to extract it from the jar resource if (!cf.exists()) { // notify the user we are extracting the store app.config System.out.println("extracting config file: " + filename); // create directories cf.getParentFile().mkdirs(); // open the input stream from the jar resource BufferedReader configIFile = null; configIFile = new BufferedReader(new InputStreamReader( getClass().getClassLoader().getResourceAsStream(filename.replace("\\", "/")))); // declare storage for the output file BufferedWriter configOFile = null; // if input file if valid, then extract the data if (configIFile != null) { try { // open the output file configOFile = new BufferedWriter(new FileWriter(cf)); // declare storage for the data from the input stream String line; // loop the config file, read each line until no more data while ((line = configIFile.readLine()) != null) { // write the data to the output file and insert the new // line terminator after each line configOFile.write(line + GlobalStack.LINESEPARATOR); // yield processing to other threads Thread.yield(); } // notify user the status of the config file System.out.println("config file extracted successfully"); } catch (Exception ex) { // if exception during processing, return it to the user throw new Exception(getClass().toString() + "//" + ex.getMessage()); } finally { // close the input file to prevent resource leaks try { configIFile.close(); } catch (Exception exi) { } // close the output file to prevent resource leaks if (configOFile != null) { try { configOFile.flush(); } catch (Exception exi) { } try { configOFile.close(); } catch (Exception exi) { } } } } } else { // config file already existed, notify user we are using it System.out.println("using config file: " + filename); } }
From source file:org.mule.providers.ldap.MuleEmbeddedTestCase.java
public synchronized void testDispatchReceiveSearchMultipleWithDelete() throws Exception { MuleClient client = new MuleClient(); final int addCount = 4; LDAPAddRequest last = null;//from ww w.j av a 2s. c om for (int i = 0; i < addCount; i++) { client.dispatch("ldap://ldap.out", last = TestHelper.getRandomEntryAddRequest(), null); } // time for processing Thread.yield(); Thread.sleep(10000); client.dispatch("ldap://ldap.out", new LDAPDeleteRequest(last.getEntry().getDN(), null), null); // time for processing Thread.yield(); Thread.sleep(10000); // we send a message on the endpoint we created, i.e. vm://Single client.dispatch("ldap://ldap.out/cn.payload", "*", null); // time for processing Thread.yield(); Thread.sleep(10000); UMOMessage result = null; UMOMessage lastResult = null; int count = 0; int tryCount = 0; // addCount * AddResponses, addCount * Search Responses, 1x Search // Result // ok, 1 delete response final int expected = (2 * addCount) + 1 - 1 + 1; // Wait until all dispatched messages are processed by DS while (tryCount < 20 && connector.getOutstandingMessageCount() != 6) { Thread.yield(); Thread.sleep(2000); logger.debug(tryCount + ".try: Outstanding are " + connector.getOutstandingMessageCount()); tryCount++; } assertTrue("Outstanding message count (" + connector.getOutstandingMessageCount() + ") not expected (" + 6 + ")", connector.getOutstandingMessageCount() == 6); // time for processing Thread.yield(); Thread.sleep(10000); logger.debug("Outstanding: " + connector.getOutstandingMessageCount()); while (true) { result = client.receive("ldap://ldap.in", 20000); if (result == null) { logger.debug("The " + count + ". message was null"); break; } logger.debug(LDAPUtils.dumpLDAPMessage(result.getPayload())); lastResult = result; count++; } if (count != expected) { logger.warn("count (" + count + ") != expected (" + expected + ")"); } assertNull("result was not null", result); assertNotNull("lastResult was null", lastResult); assertTrue(lastResult.getPayload().getClass().toString() + " instead of LDAPResponse", lastResult.getPayload() instanceof LDAPResponse); // TODO not predictable assertTrue( ((LDAPResponse) lastResult.getPayload()).getType() + " type not expected (" + LDAPMessage.SEARCH_RESULT + ")", ((LDAPResponse) lastResult.getPayload()).getType() == LDAPMessage.SEARCH_RESULT); assertTrue("count (" + count + ") != expected (" + expected + ")", count == expected); }
From source file:com.indeed.lsmtree.core.TestStore.java
public void testStore(StorageType storageType, CompressionCodec codec) throws Exception { File indexDir = new File(tmpDir, "index"); indexDir.mkdirs();//from w w w.ja v a 2s . c o m File indexLink = new File(tmpDir, "indexlink"); PosixFileOperations.link(indexDir, indexLink); File storeDir = new File(indexLink, "store"); Store<Integer, Long> store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(), new LongSerializer()).setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType) .setCodec(codec).build(); final Random r = new Random(0); final int[] ints = new int[treeSize]; for (int i = 0; i < ints.length; i++) { ints[i] = r.nextInt(); } for (final int i : ints) { store.put(i, (long) i); assertTrue(store.get(i) == i); } for (final int i : ints) { assertTrue(store.get(i) == i); } store.close(); store.waitForCompactions(); store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(), new LongSerializer()) .setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType).setCodec(codec).build(); Arrays.sort(ints); Iterator<Store.Entry<Integer, Long>> iterator = store.iterator(); int index = 0; while (iterator.hasNext()) { Store.Entry<Integer, Long> next = iterator.next(); int current = ints[index]; assertTrue(next.getKey() == ints[index]); assertTrue(next.getValue() == ints[index]); while (index < ints.length && ints[index] == current) { index++; } } assertTrue(index == ints.length); final BitSet deleted = new BitSet(); for (int i = 0; i < ints.length / 10; i++) { int deletionIndex = r.nextInt(ints.length); deleted.set(deletionIndex, true); for (int j = deletionIndex - 1; j >= 0; j--) { if (ints[j] == ints[deletionIndex]) { deleted.set(j, true); } else { break; } } for (int j = deletionIndex + 1; j < ints.length; j++) { if (ints[j] == ints[deletionIndex]) { deleted.set(j, true); } else { break; } } store.delete(ints[deletionIndex]); assertNull(store.get(ints[deletionIndex])); } iterator = store.iterator(); index = 0; while (iterator.hasNext()) { Store.Entry<Integer, Long> next = iterator.next(); while (deleted.get(index)) index++; int current = ints[index]; assertTrue(next.getKey() == ints[index]); assertTrue(next.getValue() == ints[index]); while (index < ints.length && ints[index] == current) { index++; } } while (deleted.get(index)) index++; assertTrue(index == ints.length); final int max = ints[ints.length - 1]; final AtomicInteger done = new AtomicInteger(8); for (int i = 0; i < done.get(); i++) { final int thread = i; final Store<Integer, Long> finalStore = store; new Thread(new Runnable() { @Override public void run() { try { Random r = new Random(thread); for (int i = 0; i < treeSize; i++) { int rand = r.nextInt(); int insertionindex = Arrays.binarySearch(ints, rand); Store.Entry<Integer, Long> next = finalStore.ceil(rand); boolean found = next != null; if (insertionindex >= 0 && deleted.get(insertionindex)) { assertNull(finalStore.get(ints[insertionindex])); } else { assertTrue(found == (rand <= max)); if (found) { assertTrue(next.getKey() >= rand); assertTrue(next.getKey().longValue() == next.getValue()); if (insertionindex >= 0) { assertTrue(rand == ints[insertionindex]); assertTrue(next.getKey() == rand); Long result = finalStore.get(rand); assertTrue(result == rand); } else { int nextIndex = ~insertionindex; while (deleted.get(nextIndex) && nextIndex < ints.length) nextIndex++; if (nextIndex < ints.length) { if (insertionindex != -1) assertTrue(ints[(~insertionindex) - 1] < rand); assertTrue(ints[nextIndex] + " != " + next.getKey(), ints[nextIndex] == next.getKey()); } Long result = finalStore.get(rand); assertTrue(result == null); } } } } } catch (IOException e) { throw new RuntimeException(e); } finally { done.decrementAndGet(); } } }).start(); } while (done.get() > 0) { Thread.yield(); } store.close(); }
From source file:org.crosswire.jsword.book.install.sword.AbstractSwordInstaller.java
public void install(final Book book) { // // Is the book already installed? Then nothing to do. // if (Books.installed().getBook(book.getName()) != null) // {// ww w. j a va 2s. c o m // return; // } // final SwordBookMetaData sbmd = (SwordBookMetaData) book.getBookMetaData(); // TRANSLATOR: Progress label indicating the installation of a book. {0} is a placeholder for the name of the book. String jobName = JSMsg.gettext("Installing book: {0}", sbmd.getName()); Progress job = JobManager.createJob(String.format(Progress.INSTALL_BOOK, book.getInitials()), jobName, Thread.currentThread()); URI temp = null; try { // Don't bother setting a size, we'll do it later. job.beginJob(jobName); Thread.yield(); // TRANSLATOR: Progress label indicating the Initialization of installing of a book. job.setSectionName(JSMsg.gettext("Initializing")); temp = NetUtil.getTemporaryURI("swd", ZIP_SUFFIX); download(job, packageDirectory, sbmd.getInitials() + ZIP_SUFFIX, temp); // Once the unzipping is started, we need to continue job.setCancelable(false); if (!job.isFinished()) { File dldir = SwordBookPath.getSwordDownloadDir(); IOUtil.unpackZip(NetUtil.getAsFile(temp), dldir); // TRANSLATOR: Progress label for installing the conf file for a book. job.setSectionName(JSMsg.gettext("Copying config file")); sbmd.setLibrary(NetUtil.getURI(dldir)); SwordBookDriver.registerNewBook(sbmd); } } catch (IOException e) { Reporter.informUser(this, e); job.cancel(); } catch (InstallException e) { Reporter.informUser(this, e); job.cancel(); } catch (BookException e) { Reporter.informUser(this, e); job.cancel(); } finally { job.done(); // tidy up after ourselves // This is a best effort. If for some reason it does not delete now // it will automatically be deleted when the JVM exits normally. if (temp != null) { try { NetUtil.delete(temp); } catch (IOException e) { log.warn("Error deleting temp download file.", e); } } } }
From source file:org.callimachusproject.management.CalliServer.java
public synchronized void start() throws IOException, OpenRDFException { running = true;/* w w w .ja v a 2 s .c om*/ notifyAll(); if (server != null) { try { logger.info("Callimachus is binding to {}", toString()); for (SetupRealm origin : getRealms()) { HttpHost host = URIUtils.extractHost(java.net.URI.create(origin.getRealm())); HttpClientFactory.getInstance().setProxy(host, server); } for (CalliRepository repository : repositories.values()) { repository.setCompileRepository(true); } server.start(); System.gc(); Thread.yield(); long uptime = ManagementFactory.getRuntimeMXBean().getUptime(); logger.info("Callimachus started after {} seconds", uptime / 1000.0); if (listener != null) { listener.webServiceStarted(server); } } catch (IOException e) { logger.error(e.toString(), e); } catch (OpenRDFException e) { logger.error(e.toString(), e); } } }
From source file:fi.luontola.cqrshotel.framework.EventStoreContract.java
private static void repeatInParallel(int iterations, Runnable task, Runnable invariantChecker) throws Exception { final int PARALLELISM = 10; ExecutorService executor = Executors.newFixedThreadPool(PARALLELISM + 1); Future<?> checker;//from w ww . jav a2s .c om try { checker = executor.submit(() -> { while (!Thread.interrupted()) { invariantChecker.run(); Thread.yield(); } }); List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < iterations; i++) { futures.add(executor.submit(task)); } for (Future<?> future : futures) { // will throw ExecutionException if there was a problem future.get(); } } finally { executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); } // will throw ExecutionException if there was a problem checker.get(10, TimeUnit.SECONDS); }
From source file:org.apache.hadoop.metrics2.impl.TestSinkQueue.java
private SinkQueue<Integer> newSleepingConsumerQueue(int capacity, int... values) { final SinkQueue<Integer> q = new SinkQueue<Integer>(capacity); for (int i : values) { q.enqueue(i);/*from ww w . ja v a 2s. c o m*/ } Thread t = new Thread() { @Override public void run() { try { q.consume(new Consumer<Integer>() { public void consume(Integer e) throws InterruptedException { LOG.info("sleeping"); Thread.sleep(1000 * 86400); // a long time } }); } catch (InterruptedException ex) { LOG.warn("Interrupted", ex); } } }; t.setName("Sleeping consumer"); t.setDaemon(true); // so jvm can exit t.start(); Thread.yield(); // Let the consumer consume LOG.debug("Returning new sleeping consumer queue"); return q; }
From source file:org.carrot2.core.benchmarks.memtime.MemTimeBenchmark.java
/** * Best-effort attempt to force {@link System#gc()}. */// w w w .j a v a 2 s .com private static void memClean() { System.gc(); System.gc(); Thread.yield(); }
From source file:org.apache.hadoop.hbase.rest.TestRowResource.java
private static Response putValuePB(String url, String table, String row, String column, String value) throws IOException { RowModel rowModel = new RowModel(row); rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes.toBytes(value))); CellSetModel cellSetModel = new CellSetModel(); cellSetModel.addRow(rowModel);//from w w w . j a v a 2s.c o m Response response = client.put(url, Constants.MIMETYPE_PROTOBUF, cellSetModel.createProtobufOutput()); Thread.yield(); return response; }
From source file:org.apache.hc.core5.http.benchmark.HttpBenchmark.java
public Results doExecute() throws Exception { final URL url = config.getUrl(); final long endTime = System.currentTimeMillis() + config.getTimeLimit() * 1000; final HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); final ThreadPoolExecutor workerPool = new ThreadPoolExecutor(config.getThreads(), config.getThreads(), 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { @Override//from ww w. ja v a 2s .c om public Thread newThread(final Runnable r) { return new Thread(r, "ClientPool"); } }); workerPool.prestartAllCoreThreads(); SocketFactory socketFactory = null; if ("https".equals(host.getSchemeName())) { final SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.setProtocol("SSL"); if (config.isDisableSSLVerification()) { sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }); } else if (config.getTrustStorePath() != null) { sslContextBuilder.loadTrustMaterial(new File(config.getTrustStorePath()), config.getTrustStorePassword() != null ? config.getTrustStorePassword().toCharArray() : null); } if (config.getIdentityStorePath() != null) { sslContextBuilder.loadKeyMaterial(new File(config.getIdentityStorePath()), config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null, config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null); } final SSLContext sslContext = sslContextBuilder.build(); socketFactory = sslContext.getSocketFactory(); } final BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()]; for (int i = 0; i < workers.length; i++) { workers[i] = new BenchmarkWorker(host, createRequest(host), socketFactory, config); workerPool.execute(workers[i]); } while (workerPool.getCompletedTaskCount() < config.getThreads()) { Thread.yield(); try { Thread.sleep(1000); } catch (final InterruptedException ignore) { } if (config.getTimeLimit() != -1 && System.currentTimeMillis() > endTime) { for (int i = 0; i < workers.length; i++) { workers[i].setShutdownSignal(); } } } workerPool.shutdown(); return ResultProcessor.collectResults(workers, host, config.getUrl().toString()); }