List of usage examples for java.lang Thread yield
public static native void yield();
From source file:things.common.tools.FileTools.java
/** * Make a file. If the file already exists, delete it. * It will let any exception escape./*from www . j a v a2s.c om*/ * @param name Path to the file * @return A file object * @throws Throwable */ public static File makeFile(String name) throws Throwable { File directory; String directoryPath; int fileSegment; // construct the path File target = new File(name); if (target.exists()) { int tries = ThingsConstants.FS_FILE_DELETE_RETRIES; boolean status = target.delete(); while (status != true) { tries--; if (tries == 0) throw new ThingsException("Could not delete existing file where call wanted to makeFile().", ThingsException.FILESYSTEM_ERROR_COULD_NOT_REPLACE, ThingsNamespace.ATTR_PLATFORM_FILE_PATH); System.gc(); Thread.yield(); status = target.delete(); } } else { fileSegment = name.lastIndexOf('/'); if (fileSegment > 1) { directoryPath = name.substring(0, fileSegment); directory = new File(directoryPath); if (!directory.exists()) { directory.mkdirs(); } } } return target; }
From source file:edu.upenn.cis.stormlite.LocalCluster.java
/** * Shut down the cluster//w ww . j a v a 2 s . c o m * * @param string */ public void killTopology(String string) { if (quit.getAndSet(true) == false) { while (!quit.get()) Thread.yield(); } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java
@Test public void shouldFailUntilImportExecutes() throws Exception { final ScriptEngines engines = new ScriptEngines(se -> { });/*from www. j a va2 s.c om*/ engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.emptyMap()); final Set<String> imports = new HashSet<String>() { { add("import java.awt.Color"); } }; final AtomicInteger successes = new AtomicInteger(0); final AtomicInteger failures = new AtomicInteger(0); final Thread threadImport = new Thread(() -> { engines.addImports(imports); }); // issue 1000 scripts in one thread using a class that isn't imported. this will result in failure. // while that thread is running start a new thread that issues an addImports to include that class. // this should block further evals in the first thread until the import is complete at which point // evals in the first thread will resume and start to succeed final Thread threadEvalAndTriggerImport = new Thread(() -> IntStream.range(0, 1000).forEach(i -> { try { engines.eval("Color.BLACK", new SimpleBindings(), "gremlin-groovy"); successes.incrementAndGet(); } catch (Exception ex) { if (failures.incrementAndGet() == 500) threadImport.start(); Thread.yield(); } })); threadEvalAndTriggerImport.start(); threadEvalAndTriggerImport.join(); threadImport.join(); assertTrue("Success: " + successes.intValue() + " - Failures: " + failures.intValue(), successes.intValue() > 0); assertTrue("Success: " + successes.intValue() + " - Failures: " + failures.intValue(), failures.intValue() >= 500); engines.close(); }
From source file:com.ruesga.rview.fragments.SnippetFragment.java
@Override public void onDonePressed() { if (mNeedPermissions) { return;/* www .j a v a 2 s .c om*/ } readFileContent(); Thread.yield(); if (!mReadOnly && mContentSize > 0) { //noinspection ConstantConditions Uri snippetUri = getArguments().getParcelable(EXTRA_TEMP_SNIPPET_URI); if (snippetUri != null) { Activity a = getActivity(); Fragment f = getParentFragment(); if (f instanceof OnSnippetSavedListener) { ((OnSnippetSavedListener) f).onSnippetSaved(snippetUri, mMimeType, mContentSize); } else if (a instanceof OnSnippetSavedListener) { ((OnSnippetSavedListener) a).onSnippetSaved(snippetUri, mMimeType, mContentSize); } } } }
From source file:ca.uviccscu.lp.server.main.ShutdownListener.java
@Override public void windowClosing(WindowEvent e) { if (Shared.hashInProgress) { JOptionPane.showMessageDialog(null, "Closing not allowed - stop or finish hashing first!", "Hash in progress!", JOptionPane.WARNING_MESSAGE); } else {/*from w ww . j a va 2 s . c o m*/ SwingWorker worker = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { try { int ans1 = JOptionPane.showConfirmDialog(null, "Are you sure you want to shutdown? " + "Clients will switch to passive mode until restarted.", "Confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (ans1 == JOptionPane.OK_OPTION) { l.debug("MainFrame window closing requested"); MainFrame.lockInterface(); MainFrame.setReportingActive(); MainFrame.updateTask("Shutting down", true); MainFrame.updateProgressBar(0, 0, 0, "Shutting down settings manager!", true, true); l.trace("Shutting down settings manager and saving session"); int ans2 = JOptionPane.showConfirmDialog(null, "Do you want to save the games list", "Save confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (ans2 == JOptionPane.OK_OPTION) { SettingsManager.showSaveSettingsDialog(); } SettingsManager.shutdown(); l.trace("OK"); l.trace("Stopping net manager"); MainFrame.updateProgressBar(0, 0, 0, "Shutting down net manager!", true, true); ServerNetManager.shutdown(); l.trace("OK"); l.trace("Shutting down tracker manager - might have errors here!"); MainFrame.updateProgressBar(0, 0, 0, "Shutting down azureus - might take a while!", true, true); //Errors due to Azureus stupid shutdown thread killing routine(see AzureusCoreImpl) //Basically it kills all other threads it doesnt recognise on JVM and then terminates //Not designed to work with other application, and so it also kills the shutdown thread = BAD //Library modified to prevent system shutdown, but exceptions still coming - irrelevant TrackerManager.shutdown(); Thread.yield(); l.trace("OK"); Thread.yield(); Thread.sleep(5000); while (!Shared.azShutdownDone) { try { l.trace("Awaiting az shutdown"); Thread.sleep(500); } catch (InterruptedException ex) { l.error("Az shutdown monitor interrupted", ex); } } MainFrame.updateProgressBar(0, 0, 0, "Cleaning temporary files - might take a while!", true, true); File f = new File(Shared.workingDirectory); /* //delete until files unlocked or timeout if (!deleteFolder(f, true, 3000, 15000)) { l.trace("Advanced file deletion measures required"); releaseLocks(); deleteFolder(f, false, 0, 0); //Advanced thread killing, stolen from azureus...except now it kills itself l.error("Delete timeout - attempting threadicide"); l.trace("Starting thread killing"); //First kill azureus SM - allows to do whatever we want with threads l.trace("Removed SM"); System.setSecurityManager(null); // ThreadGroup tg = Thread.currentThread().getThreadGroup(); while (tg.getParent() != null) { tg = tg.getParent(); } Thread[] threads = new Thread[tg.activeCount() + 1024]; tg.enumerate(threads, true); //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks for (int i = 0; i < threads.length; i++) { Thread th = threads[i]; if (th != null && th != Thread.currentThread() && AEThread2.isOurThread(th)) { l.trace("Stopping " + th.getName()); try { th.stop(); l.trace("ok"); } catch (SecurityException e) { l.trace("Stop vetoed by SM", e); } } } // deleteFolder(f, false, 0, 0); l.error("Trying to stop more threads, list:"); //List remaining threads ThreadGroup tg2 = Thread.currentThread().getThreadGroup(); while (tg2.getParent() != null) { tg2 = tg2.getParent(); } //Object o = new Object(); //o.notifyAll(); Thread[] threads2 = new Thread[tg2.activeCount() + 1024]; tg2.enumerate(threads2, true); //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks for (int i = 0; i < threads2.length; i++) { Thread th = threads2[i]; if (th != null) { l.trace("Have thread: " + th.getName()); if (th != null && th != Thread.currentThread() && (AEThread2.isOurThread(th) || isAzThread(th))) { l.trace("Stopping " + th.getName()); try { th.stop(); l.trace("ok"); } catch (SecurityException e) { l.trace("Stop vetoed by SM", e); } } } } try { Utils.cleanupDir(); l.trace("OK"); } catch (IOException e) { l.trace("Cleaning failed after more thread cleanup", e); Thread.yield(); } threadCleanup(f); l.error("Last resort - scheduling delete on JVM exit - might FAIL, CHECK MANUALLY"); try { FileUtils.forceDeleteOnExit(f); } catch (IOException iOException) { l.fatal("All delete attempts failed - clean manually"); } } File test = new File("C:\\AZTest\\AZ\\logs\\debug_1.log"); test.deleteOnExit(); try { Thread.sleep(30000); } catch (InterruptedException ex) { java.util.logging.Logger.getLogger(ShutdownListener.class.getName()).log(Level.SEVERE, null, ex); } * */ threadReadout(); try { Utils.cleanupDir(); l.trace("OK"); } catch (IOException e) { l.trace("Cleaning failed - expected due to stupid Azureus file lock", e); Thread.yield(); } System.exit(0); return null; } else { return null; } } catch (Exception ex) { l.fatal("Exception during shutdown!!!", ex); //just end it System.exit(4); return null; } } }; worker.execute(); } }
From source file:org.apache.zeppelin.notebook.NotebookTest.java
@Test public void testRunAll() throws IOException { Note note = notebook.createNote();//from w w w . j a v a 2 s. co m note.getNoteReplLoader().setInterpreters(factory.getDefaultInterpreterSettingList()); Paragraph p1 = note.addParagraph(); p1.setText("p1"); Paragraph p2 = note.addParagraph(); p2.setText("p2"); assertEquals(null, p2.getResult()); note.runAll(); while (p2.isTerminated() == false || p2.getResult() == null) Thread.yield(); assertEquals("repl1: p2", p2.getResult().message()); }
From source file:Main.java
/** * Compute the integral root of x to a given scale, x >= 0. * Use Newton's algorithm.//from ww w . j a v a 2s. c o m * @param x the value of x * @param index the integral root value * @param scale the desired scale of the result * @return the result value */ public static BigDecimal intRoot(BigDecimal x, long index, int scale) { // Check that x >= 0. if (x.signum() < 0) { throw new IllegalArgumentException("x < 0"); } int sp1 = scale + 1; BigDecimal n = x; BigDecimal i = BigDecimal.valueOf(index); BigDecimal im1 = BigDecimal.valueOf(index - 1); BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1); BigDecimal xPrev; // The initial approximation is x/index. x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN); // Loop until the approximations converge // (two successive approximations are equal after rounding). do { // x^(index-1) BigDecimal xToIm1 = intPower(x, index - 1, sp1); // x^index BigDecimal xToI = x.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN); // n + (index-1)*(x^index) BigDecimal numerator = n.add(im1.multiply(xToI)).setScale(sp1, BigDecimal.ROUND_HALF_EVEN); // (index*(x^(index-1)) BigDecimal denominator = i.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN); // x = (n + (index-1)*(x^index)) / (index*(x^(index-1))) xPrev = x; x = numerator.divide(denominator, sp1, BigDecimal.ROUND_DOWN); Thread.yield(); } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0); return x; }
From source file:org.apache.zeppelin.helium.HeliumApplicationFactoryTest.java
@Test public void testUnloadOnParagraphRemove() throws IOException { // given/*from ww w .j a va 2 s .c o m*/ HeliumPackage pkg1 = new HeliumPackage(HeliumType.APPLICATION, "name1", "desc1", "", HeliumTestApplication.class.getName(), new String[][] {}, "", ""); Note note1 = notebook.createNote(anonymous); interpreterSettingManager.setInterpreters("user", note1.getId(), interpreterSettingManager.getDefaultInterpreterSettingList()); Paragraph p1 = note1.addParagraph(AuthenticationInfo.ANONYMOUS); // make sure interpreter process running p1.setText("%mock1 job"); p1.setAuthenticationInfo(anonymous); note1.run(p1.getId()); while (p1.isTerminated() == false || p1.getResult() == null) Thread.yield(); assertEquals(0, p1.getAllApplicationStates().size()); String appId = heliumAppFactory.loadAndRun(pkg1, p1); ApplicationState app = p1.getApplicationState(appId); while (app.getStatus() != ApplicationState.Status.LOADED) { Thread.yield(); } // when remove paragraph note1.removeParagraph("user", p1.getId()); // then assertEquals(ApplicationState.Status.UNLOADED, app.getStatus()); // clean notebook.removeNote(note1.getId(), anonymous); }
From source file:net.lightbody.bmp.proxy.jetty.util.Pool.java
public PondLife get(int timeoutMs) throws Exception { PondLife pl = null;// w w w . j a va2 s. co m // Defer to other threads before locking if (_available < _min) Thread.yield(); int new_id = -1; // Try to get pondlife without creating new one. synchronized (this) { // Wait if none available. if (_running > 0 && _available == 0 && _size == _pondLife.length && timeoutMs > 0) wait(timeoutMs); // If still running if (_running > 0) { // if pondlife available if (_available > 0) { int id = _index[--_available]; pl = _pondLife[id]; } else if (_size < _pondLife.length) { // Reserve spot for a new one new_id = reservePondLife(false); } } // create reserved pondlife if (pl == null && new_id >= 0) pl = newPondLife(new_id); } return pl; }
From source file:com.teletalk.jserver.util.SpillOverByteArrayOutputStream.java
/** * Reset the stream, cleans up resources and deletes any spill over file that has been created. */// w w w. j a v a2 s . c om public void reset() { this.byteArrayOutputStream = null; this.bytesWritten = 0; this.spillOverFailed = false; if (this.spillOverFileOutputStream != null) { try { this.spillOverFileOutputStream.close(); } catch (Exception e) { } Thread.yield(); } this.spillOverFileOutputStream = null; if (this.spillOverFile != null) { if (this.spillOverFile.delete()) this.spillOverFile = null; } }