List of usage examples for java.lang Thread yield
public static native void yield();
From source file:org.apparatus_templi.Coordinator.java
public static void main(String argv[]) { Log.setLogLevel(Log.LEVEL_DEBUG);/*from w w w .j a va2 s . c om*/ Log.setLogToConsole(true); // disable dock icon in MacOS System.setProperty("apple.awt.UIElement", "true"); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // start the system tray icon listener. The sysTray should be save (but useless) in a // headless environment sysTray = new SysTray(); // parse command line options parseCommandLineOptions(argv); // set debug level switch (prefs.getPreference(Prefs.Keys.debugLevel)) { case "err": Log.setLogLevel(Log.LEVEL_ERR); break; case "warn": Log.setLogLevel(Log.LEVEL_WARN); break; default: Log.setLogLevel(Log.LEVEL_DEBUG); } Log.d(TAG, "SERVICE STARTING"); Log.c(TAG, "Starting"); // open the serial connection openSerialConnection(); // start the message center messageCenter = MessageCenter.getInstance(); messageCenter.setSerialConnection(serialConnection); // block until the local Arduino is ready System.out.print(TAG + ":" + "Waiting for local link to be ready."); if (!(serialConnection instanceof DummySerialConnection)) { byte[] sBytes = null; try { sBytes = messageCenter.readBytesUntil((byte) 0x0A); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sString = new String(sBytes); if (sString.endsWith("READY")) { connectionReady = true; } if (!connectionReady) { Coordinator.exitWithReason("could not find a local Arduino connection, exiting"); } else { Log.c(TAG, "Local link ready."); } } else { connectionReady = true; Log.c(TAG, "Local dummy link ready"); } // query for remote modules. Since the modules may be slow in responding // + we will wait for a few seconds to make sure we get a complete list System.out.print(TAG + ":" + "Querying modules (6s wait)."); messageCenter.beginReadingMessages(); // begin processing incoming messages new Thread(messageCenter).start(); // if we are using the dummy serial connection then there is no point in // waiting // + 6 seconds for a response from the modules if (!(serialConnection instanceof DummySerialConnection)) { queryRemoteModules(); for (int i = 0; i < 6; i++) { if (messageCenter.isMessageAvailable()) { routeIncomingMessage(messageCenter.getMessage()); } System.out.print("."); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println(); if (remoteModules.size() > 0) { Log.c(TAG, "Found " + remoteModules.size() + " modules :" + remoteModules.toString()); } else { Log.c(TAG, "Did not find any remote modules."); } // initialize and start all drivers startDrivers(); // Add a shutdown hook so that the drivers can be notified when // + the system is going down. Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { Log.d(TAG, "system is going down. Notifying all drivers."); sysTray.setStatus(SysTray.Status.TERM); Thread.currentThread().setName("Shutdown Hook"); // Coordinator.sendNotificationEmail("Shutdown Hook triggered"); // cancel any pending driver restarts scheduledWakeUps.clear(); for (String driverName : loadedDrivers.keySet()) { Log.d(TAG, "terminating driver '" + driverName + "'"); loadedDrivers.get(driverName).terminate(); Log.d(TAG, "notified driver '" + driverName + "'"); } // give the drivers ~4s to finalize their termination long wakeTime = System.currentTimeMillis() + 4 * 1000; while (System.currentTimeMillis() < wakeTime) { // do a non-blocking sleep so that incoming message can still be routed } // System.exit(0); } }); // start the web interface try { startWebServer(null); } catch (UnknownHostException e1) { // if we cant start the web server then the service should shut down Log.t(TAG, "can not start web server: " + e1.getMessage()); Coordinator.exitWithReason("unable to start web server"); } // the service should be up and running, send a notification email String serverUp = "Service has started normally."; String newLocation = webServer.getProtocol() + webServer.getServerLocation() + ":" + webServer.getPort() + "/index.html"; StringBuilder newAddress = new StringBuilder(); newAddress.append( "Web server restarted, available at: <a href='" + newLocation + "'>" + newLocation + "</a>"); sendNotificationEmail(new String[] { serverUp, newAddress.toString() }); // enter main loop while (true) { // TODO keep track of the last time a message was sent to/received // from each remote module // + if the time period is too great, then re-query the remote // modules, possibly removing // + them from the known list if no response is detected // Check for incoming messages, only process the first byte before // breaking off // + to a more appropriate method if (messageCenter.isMessageAvailable()) { routeIncomingMessage(messageCenter.getMessage()); } // Check for scheduled driver wake ups. for (Driver d : scheduledWakeUps.keySet()) { Long wakeTime = scheduledWakeUps.get(d); Long curTime = System.currentTimeMillis(); if (wakeTime <= curTime && wakeTime != 0) { try { wakeDriver(d.getName()); } catch (Exception e) { Log.e(TAG, "error restarting driver '" + d.getName() + "'"); scheduledWakeUps.remove(d); } } } Thread.yield(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:MyZone.Settings.java
private boolean saveXML(String filename, Document dom) { File file = null;// w ww . jav a2 s .c o m FileChannel channel = null; FileLock lock = null; FileOutputStream toWrite = null; try { if (!new File(filename).exists()) { String dirName = filename.substring(0, filename.lastIndexOf("/")); boolean success = (new File(dirName)).mkdirs(); if (!success && !(new File(dirName)).exists()) { return false; } OutputFormat format = new OutputFormat(dom); format.setIndenting(true); file = new File(filename); toWrite = new FileOutputStream(file, false); XMLSerializer serializer = new XMLSerializer(toWrite, format); serializer.serialize(dom); } else { file = new File(filename); toWrite = new FileOutputStream(file, false); channel = toWrite.getChannel(); while ((lock = channel.tryLock()) == null) { Thread.yield(); } OutputFormat format = new OutputFormat(dom); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer(toWrite, format); serializer.serialize(dom); return true; } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } return false; } finally { try { if (lock != null) { lock.release(); } if (channel != null) { channel.close(); } if (toWrite != null) { toWrite.flush(); toWrite.close(); } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } return false; } } return false; }
From source file:org.voltdb.TableHelper.java
/** * Delete rows in a VoltDB table that has a bigint pkey where pkey values are odd. * Works best when pkey values are contiguous and start around 0. * * Exists mostly to force compaction on tables loaded with fillTableWithBigintPkey. * Though if you have an even number of sites, this won't work. It'll need to be * updated to delete some other pattern that's a bit more generic. Right now it * works great for my one-site testing.//from w w w . ja va 2 s . co m * */ public static long deleteEveryNRows(VoltTable table, Client client, int n) throws Exception { // find the primary key, assume first col if not found int pkeyColIndex = getBigintPrimaryKeyIndexIfExists(table); if (pkeyColIndex == -1) { pkeyColIndex = 0; assert (table.getColumnType(0).isInteger()); } String pkeyColName = table.getColumnName(pkeyColIndex); VoltTable result = client .callProcedure("@AdHoc", String.format("select %s from %s order by %s desc limit 1;", pkeyColName, TableHelper.getTableName(table), pkeyColName)) .getResults()[0]; long maxId = result.getRowCount() > 0 ? result.asScalarLong() : 0; System.out.printf("Deleting odd rows with pkey ids in the range 0-%d\n", maxId); // track outstanding responses so 10k can be out at a time final AtomicInteger outstanding = new AtomicInteger(0); final AtomicLong deleteCount = new AtomicLong(0); ProcedureCallback callback = new ProcedureCallback() { @Override public void clientCallback(ClientResponse clientResponse) throws Exception { outstanding.decrementAndGet(); if (clientResponse.getStatus() != ClientResponse.SUCCESS) { System.out.println("Error in deleter callback:"); System.out.println(((ClientResponseImpl) clientResponse).toJSONString()); assert (false); } VoltTable result = clientResponse.getResults()[0]; long modified = result.asScalarLong(); assert (modified <= 1); deleteCount.addAndGet(modified); } }; // delete 100k rows at a time until nothing comes back long deleted = 0; final String deleteProcName = table.m_extraMetadata.name.toUpperCase() + ".delete"; for (int i = 1; i <= maxId; i += n) { client.callProcedure(callback, deleteProcName, i); outstanding.incrementAndGet(); deleted++; if ((deleted % 100000) == 0) { System.out.printf("Sent %d total delete invocations (%.1f%% of range).\n", deleted, (i * 100.0) / maxId); } // block while 1000 txns are outstanding while (outstanding.get() >= 1000) { Thread.yield(); } } // block until all calls have returned while (outstanding.get() > 0) { Thread.yield(); } System.out.printf("Deleted %d odd rows\n", deleteCount.get()); return deleteCount.get(); }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Starts the Stand Alone service engine. * /*from w ww. j a va 2 s . co m*/ * Gets the connection from the pool and Continuously scans the * PROCESS_REQUEST table for queued standalone requests and executes them * sequentially * * <p> * Scanning continues in a loop until the bEngineTerminated_ attribute is * false. This attribute is set to true when the engine is interrupted, and * this loop exits. * </p> * <p> * The query picks up requests, from the table PROCESS_REQUEST, that have * the Req_Stat='Q' and GRP_ST_IND = 'S'. If requests are found then each * record is processed sequentially If no records are found then the engine * waits for a specified time (picked up from property file) and then * resumes scanning * </p> * * <p> * This method will <b>spawn Threads</b> for processing stand alone * requests, thus taking maximum advantage of the CPU. The threads are * created by taking into account the number of connections available in the * pool - 2. As two connections are internally used by the Engine, One for * making updates for status and another for processing Grouped Requests. * </p> * * @throws CProcessRequestEngineException * */ private void startServiceForNormalRequests() throws CProcessRequestEngineException { boolean isQueuedReqFound = false; ProcessRequestController objPrCont_ = null; StringBuffer reqLogFileName; StringBuffer reqLogFileUrl; // final int iNoOfThreads_ = (bValidLicense_?Integer.MAX_VALUE:2); try { reqLogFileName = new StringBuffer(50); reqLogFileUrl = new StringBuffer(50); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Starting StandAlone Engine ...."); } if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.info("Getting JDBC Connection for the StandAlone Engine ...."); } // staticConnection_ = // poolManager_.getConnection(CSettings.get("pr.dsforstandaloneeng")); DataSource ds = dataSourceFactory_.getDataSource(CSettings.get("pr.dsforstandaloneeng")); if (ds == null) { throw new CProcessRequestEngineException("NullPointerException for DataSource"); } staticConnection_ = ds.getConnection(); CDynamicDataContainer objDdc_ = new CDynamicDataContainer(); objDdc_.addWhereClause(FILTER_CONDITION); objDdc_.addOrderByClause(ORDER_BY_CLAUSE); ProcessRequestEntityBean objPrEb_ = new ProcessRequestEntityBean(); objPrCont_ = new ProcessRequestController(staticConnection_); setRebootCounter(-1); // Ideally here the Engine can be considered // as started. checkClusterPRE(); if (!tMain_.isInterrupted() || !bEngineTerminated_.get()) { objEngineLogger_.log(LogLevel.NOTICE, "Stand Alone Engine Started.."); } Iterator<RequestStatusVO> failOverRequestIterator = context_.getFailedOverRequests().iterator(); while (!tMain_.isInterrupted()) { context_.setPREActive(true); boolean bTerminate = false; // try { // LicenseVerifier.verify(readLicense()); // } catch (LicenseContentException lce) { // bTerminate = true; // objEngineLogger_.fatal(lce.getLocalizedMessage()); // } catch (Exception e) { // bTerminate = true; // objEngineLogger_.fatal(e.getLocalizedMessage()); // } if (bTerminate) { if (tEngine_ != null) { tEngine_.interrupt(); } break; } try { isQueuedReqFound = false; boolean failOverRequest = false; if (!bEngineTerminated_.get()) { if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Entered infintite loop, Initializing Request Entity Bean ...."); } setReboot(false); objPrEb_.initialize(); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Building query ...."); } if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Querying for queued requests ...."); } if (failOverRequestIterator.hasNext()) { RequestStatusVO vo = failOverRequestIterator.next(); objEngineLogger_.log(LogLevel.NOTICE, "Re-Executing Failed-Over Request #" + vo.getReqId()); objPrEb_.setReqId(vo.getReqId()); objPrEb_.setReqStat(vo.getStatus()); objDdc_.build(staticConnection_, objPrEb_); objDdc_.setMaximumFetchSize(iMaximumFetchSizeAtATime_); objDdc_.setPartialFetch(true); failOverRequestIterator.remove(); isQueuedReqFound = objDdc_.executeQuery(staticConnection_, objPrCont_, objPrEb_); failOverRequest = true; } else { objPrEb_.setReqStat(REQUEST_STATUS.QUEUED.getID()); objPrEb_.setGrpStInd(REQUEST_TYPE.STANDALONE.getID()); objPrEb_.setScheduledTime(getCurrentTimestamp(staticConnection_)); objDdc_.build(staticConnection_, objPrEb_, hmWhereCondition_); objDdc_.setMaximumFetchSize(iMaximumFetchSizeAtATime_); objDdc_.setPartialFetch(true); // This has been added later by Kedar on 3/1/2003 isQueuedReqFound = objDdc_.executeQuery(staticConnection_, objPrCont_, objPrEb_); failOverRequest = false; } } // If engine is not terminated then only do the above // stuff. if (isQueuedReqFound) {// pending requests exist if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Queued requests exists ...."); } // The bEngineTerminated_ flag with an OR condition was // added on 21.01.2004 by Kedar. // This is because if the StopEngine tires terminate the // engine and if there is a process // already running then the engine should not enter the // while loop. while (objDdc_.next() && !(tMain_.isInterrupted() || bEngineTerminated_.get())) { if (iThreadCounter_.get() <= iStandAloneMaximumThread_ // && iThreadCounter_.get() <= licContent_ // .getConsumerAmount() ) // if ( iThreadCounter_ < // CSettings.getInt(("pr.standalonemaximumthreads", // "2")) && iThreadCounter_ <= // licContent_.getConsumerAmount()) { ProcessRequestEntityBean objPrEb = (ProcessRequestEntityBean) objDdc_.get(); reqLogFileName.delete(0, reqLogFileName.length()); reqLogFileUrl.delete(0, reqLogFileUrl.length()); reqLogFileName.append(strReqLogFilePath_); reqLogFileName.append(objPrEb.getReqId()); reqLogFileName.append("."); reqLogFileName.append(strReqLogFileExtension_); reqLogFileUrl.append(strReqLogFileUrl_); reqLogFileUrl.append(objPrEb.getReqId()); reqLogFileUrl.append("."); reqLogFileUrl.append(strReqLogFileExtension_); // objEngineLogger_.info("Initialize Request Log File ...."); updateRequestStatus(staticConnection_, objPrCont_, objPrEb, REQUEST_STATUS.LAUNCHING, reqLogFileUrl.toString()); // Create a new thread and start the process. // Increament the Thread counter so that if // thread counter reaches // Maximum of the connections available in pool // then the engine should not spawn a new // thread. ThreadProcess tp = new ThreadProcess("Thread-ReqId#" + objPrEb.getReqId()); // tp.join(); //Joins the new thread to the // parent (tEngine). addStandAloneProcess(tp); tp.setProcessRequestEntityBean(objPrEb); tp.setLogFileName(reqLogFileName.toString()); tp.setLogFileNameURL(reqLogFileUrl.toString()); tp.setPool(dataSourceFactory_); // So that the // ThreadProcess // can request // connection // from Pool tp.setFailedOver(failOverRequest); tp.start(); } // if ( iThreadCounter_ < // iTotalConnectionsInPool_) // If all the available threads are spawned then // wait for 10 seconds. This should be // parameterised. // If thread.sleep is not called then for that while // loop it will take a huge CPU time and rest of the // threads will be slow. // The above comment is debatable. So commented // currently. boolean bInWaitMode = false; if (iThreadCounter_.get() > iStandAloneMaximumThread_) { bInWaitMode = true; if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Maximum thread spawning capacity (#" + (iThreadCounter_.get() - 1) + ") has reached. Going into Wait mode till one of the JOB gets over."); } } long lCurrentTime = System.currentTimeMillis(); while (iThreadCounter_.get() > iStandAloneMaximumThread_) { // try // { // Thread.sleep(10000); // } // catch (InterruptedException ie) // { // System.exit(1); // } } long lWaitTime = System.currentTimeMillis() - lCurrentTime; if (bInWaitMode) { bInWaitMode = false; if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Wait Over. Waited for #" + lWaitTime + " milliseconds for some JOB to get over."); } } } // end of while(objDdc.next()) } // end of if objDdc.getTotalRows() > 0 else { if (!failOverRequestIterator.hasNext()) { // no failover // jobs. lWaitInterval_ = (Math.abs(Long.parseLong(CSettings.get("pr.waitinterval")))); if (!(bEngineTerminated_.get() || tMain_.isInterrupted())) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info(mfSleepMessageForEngine_ .format(new Object[] { "StandAlone", lWaitInterval_ })); } try { Thread.yield(); TimeUnit.SECONDS.sleep(lWaitInterval_); // Thread.sleep(lWaitInterval_); } catch (InterruptedException ie) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Engine Thread Interrupted .."); } break; } } else { if (bEngineTerminated_.get()) { tMain_.interrupt(); } } } } // end of else } catch (CDynamicDataContainerException cdce) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the Engine // itself and so engine should get terminated. stopMessageForEmail_ = exceptionToString(cdce); objEngineLogger_.fatal("CDynamicQueryException Caught. Terminating StandAlone Engine", cdce); setReboot(true); break; } catch (CDynamicQueryException cdqe) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the Engine // itself and so engine should get terminated. stopMessageForEmail_ = exceptionToString(cdqe); objEngineLogger_.fatal("CDynamicQueryException Caught. Terminating StandAlone Engine", cdqe); setReboot(true); break; } catch (IOException ioe) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the // Connection. try { staticConnection_ = refreshJDBCConnection(4, staticConnection_, CSettings.get("pr.dsforstandaloneeng")); } catch (Exception e) { stopMessageForEmail_ = exceptionToString(ioe); objEngineLogger_.fatal("IOException Caught. Terminating StandAlone Engine", ioe); setReboot(true); ; break; } } catch (SQLException se) { // This is under the assumption that the SQL Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the // Connection. objEngineLogger_.error("SQLException caught", se); try { staticConnection_ = refreshJDBCConnection(4, staticConnection_, CSettings.get("pr.dsforstandaloneeng")); // StackTraceElement[] elements = se.getStackTrace(); // for (int i = 0; i < elements.length; i++) { // // } } catch (Exception e) { stopMessageForEmail_ = exceptionToString(se); objEngineLogger_.fatal("SQLException Caught. Terminating StandAlone Engine", se); setReboot(true); break; } } catch (RuntimeException ree) { objEngineLogger_.error("Runtime Exception Caught", ree); // Just catch; no need to throw exception. } catch (CProcessRequestEngineException cree) { objEngineLogger_.error("CProcessRequestEngineException Caught", cree); // Just catch; no need to throw exception. } catch (Exception e) { objEngineLogger_.error("Exception Caught", e); // Just catch; no need to throw exception. } catch (Error e) { if (e instanceof ThreadDeath) { objEngineLogger_.fatal("Process killed through the PRE Web Service"); } else { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal(e); throw e; } } } // end of while true } catch (ConnectException e) { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal("ConnectException Caught. Terminating StandAlone Engine", e); if (getRebootCounter() > 0) { setReboot(true); } } catch (SQLException e) { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal("SQLException Caught. Terminating StandAlone Engine", e); if (getRebootCounter() > 0) { setReboot(true); } } catch (IOException e) { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal("IOException Caught. Terminating StandAlone Engine", e); if (getRebootCounter() > 0) { setReboot(true); } } catch (Exception e) { throw new CProcessRequestEngineException(e.getMessage(), e); } // end of 1st try catch block finally { ((PREContextImpl) context_).setPREActive(false); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Releasing Stand Alone Resources And Confirming Termination ..."); } if (objPrCont_ != null) { try { objPrCont_.close(); } catch (SQLException e) { objEngineLogger_.error("Caught exception while closing PRController.", e); } } // pool_.stopShrinking(); reqLogFileName = null; // Nullifying the variables. reqLogFileUrl = null; // Nullifying the variables. if (tInterrupt_ != null) { if (tInterrupt_.isAlive()) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Interrupting Shutdown Hook from Stand Alone Requests..."); } tInterrupt_.interrupt(); } } bEngineTerminated_.set(true); } }
From source file:org.apache.hadoop.hbase.master.TestDistributedLogSplitting.java
private void waitForCounter(AtomicLong ctr, long oldval, long newval, long timems) { long curt = System.currentTimeMillis(); long endt = curt + timems; while (curt < endt) { if (ctr.get() == oldval) { Thread.yield(); curt = System.currentTimeMillis(); } else {/*from w ww .j a v a 2s . c om*/ assertEquals(newval, ctr.get()); return; } } assertTrue(false); }
From source file:org.xmlsh.sh.shell.Shell.java
public boolean shutdown(boolean force, long waitTime) { getLogger().entry(force, waitTime);/*from w w w. j a v a 2 s. c o m*/ if (mClosed) return getLogger().exit(true); // Mark us done mExitVal = Integer.valueOf(0); long end = System.currentTimeMillis() + waitTime; waitTime = Util.nextWait(end, waitTime); // Break all doBreak(-1); List<ShellThread> children = getChildren(false); if (force) { if (children != null) { synchronized (children) { children = new ArrayList<>(children); } for (ShellThread c : children) { waitTime = Util.nextWait(end, waitTime); killChild(c, waitTime); } } terminateChildProcesses(); } waitTime = Util.nextWait(end, waitTime); waitAtMostChildren(0, waitTime); Thread.yield(); return getLogger().exit(mClosed); }
From source file:processing.core.PApplet.java
/** * Main method for the primary animation thread. *///from w w w. j a v a2s.co m public void run() { // not good to make this synchronized, locks things up long beforeTime = System.nanoTime(); long overSleepTime = 0L; int noDelays = 0; // Number of frames with a delay of 0 ms before the // animation thread yields to other running threads. final int NO_DELAYS_PER_YIELD = 15; while ((Thread.currentThread() == thread) && !finished) { while (paused) { try { Thread.sleep(100L); } catch (InterruptedException e) { // ignore? } } // Don't resize the renderer from the EDT (i.e. from a // ComponentEvent), // otherwise it may attempt a resize mid-render. // if (resizeRequest) { // resizeRenderer(resizeWidth, resizeHeight); // resizeRequest = false; // } // render a single frame if (g != null) g.requestDraw(); // g.requestDraw(); // surfaceView.requestDraw(); // removed in android // if (frameCount == 1) { // // Call the request focus event once the image is sure to be on // // screen and the component is valid. The OpenGL renderer will // // request focus for its canvas inside beginDraw(). // // // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html // //println("requesting focus"); // requestFocus(); // } // wait for update & paint to happen before drawing next frame // this is necessary since the drawing is sometimes in a // separate thread, meaning that the next frame will start // before the update/paint is completed long afterTime = System.nanoTime(); long timeDiff = afterTime - beforeTime; // System.out.println("time diff is " + timeDiff); long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { // Thread.sleep(sleepTime / 1000000L); // nanoseconds -> // milliseconds Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L)); noDelays = 0; // Got some sleep, not delaying anymore } catch (InterruptedException ex) { } overSleepTime = (System.nanoTime() - afterTime) - sleepTime; // System.out.println(" oversleep is " + overSleepTime); } else { // sleepTime <= 0; the frame took longer than the period // excess -= sleepTime; // store excess time value overSleepTime = 0L; if (noDelays > NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); } // if this isn't just a pause, shut it all down if (!paused) { stop(); // call to shutdown libs? // If the user called the exit() function, the window should close, // rather than the sketch just halting. if (exitCalled) { exit2(); } } }
From source file:com.processing.core.PApplet.java
/** * Main method for the primary animation thread. *///from w w w . ja v a 2 s.c o m public void run() { // not good to make this synchronized, locks things up long beforeTime = System.nanoTime(); long overSleepTime = 0L; int noDelays = 0; // Number of frames with a delay of 0 ms before the // animation thread yields to other running threads. final int NO_DELAYS_PER_YIELD = 15; while ((Thread.currentThread() == thread) && !finished) { while (paused) { try { Thread.sleep(100L); } catch (InterruptedException e) { //ignore? } } // Don't resize the renderer from the EDT (i.e. from a ComponentEvent), // otherwise it may attempt a resize mid-render. // if (resizeRequest) { // resizeRenderer(resizeWidth, resizeHeight); // resizeRequest = false; // } // render a single frame if (g != null) g.requestDraw(); // g.requestDraw(); // surfaceView.requestDraw(); // removed in android // if (frameCount == 1) { // // Call the request focus event once the image is sure to be on // // screen and the component is valid. The OpenGL renderer will // // request focus for its canvas inside beginDraw(). // // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html // //println("requesting focus"); // requestFocus(); // } // wait for update & paint to happen before drawing next frame // this is necessary since the drawing is sometimes in a // separate thread, meaning that the next frame will start // before the update/paint is completed long afterTime = System.nanoTime(); long timeDiff = afterTime - beforeTime; //System.out.println("time diff is " + timeDiff); long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { // Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L)); noDelays = 0; // Got some sleep, not delaying anymore } catch (InterruptedException ex) { } overSleepTime = (System.nanoTime() - afterTime) - sleepTime; //System.out.println(" oversleep is " + overSleepTime); } else { // sleepTime <= 0; the frame took longer than the period // excess -= sleepTime; // store excess time value overSleepTime = 0L; if (noDelays > NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); } // if this isn't just a pause, shut it all down if (!paused) { stop(); // call to shutdown libs? // If the user called the exit() function, the window should close, // rather than the sketch just halting. if (exitCalled) { exit2(); } } }
From source file:org.apache.geode.internal.cache.OplogJUnitTest.java
/** * This is used to test bug 35012 where a remove operation on a key gets unrecorded due to * switching of Oplog if it happens just after the remove operation has destroyed the in memory * entry & is about to acquire the readlock in DiskRegion to record the same. If the Oplog has * switched during that duration , the bug would appear * *///from w w w.j a v a 2 s .c o m @Test public void testBug35012() { final int MAX_OPLOG_SIZE = 500; diskProps.setMaxOplogSize(MAX_OPLOG_SIZE); diskProps.setPersistBackup(true); diskProps.setRolling(false); diskProps.setSynchronous(true); diskProps.setOverflow(false); final byte[] val = new byte[200]; try { region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL); region.put("key1", val); region.put("key2", val); region.put("key3", val); final Thread th = new Thread(new Runnable() { public void run() { region.remove("key1"); } }); // main thread acquires the write lock ((LocalRegion) region).getDiskRegion().acquireWriteLock(); try { th.start(); Thread.yield(); DiskRegion dr = ((LocalRegion) region).getDiskRegion(); dr.testHook_getChild().forceRolling(dr); } finally { ((LocalRegion) region).getDiskRegion().releaseWriteLock(); } ThreadUtils.join(th, 30 * 1000); region.close(); region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL); assertEquals(region.size(), 2); } catch (Exception e) { this.logWriter.error("Exception occurred ", e); fail("The test could not be completed because of exception .Exception=" + e); } closeDown(); }
From source file:com.gemstone.gemfire.internal.cache.OplogJUnitTest.java
/** * This tests the bug which caused the oplogRoller to attempt to roll a * removed entry whose value is Token.Removed This bug can occur if a remove * operation causes oplog switching & hence roller thread gets notified, & the * roller thread obtains the iterator of the concurrent region map before the * remove//www . ja v a 2 s . c o m * * @author Asif */ @Test public void testBug34702() { final int MAX_OPLOG_SIZE = 500 * 2; diskProps.setMaxOplogSize(MAX_OPLOG_SIZE); diskProps.setPersistBackup(true); diskProps.setRolling(true); diskProps.setSynchronous(true); diskProps.setOverflow(false); final byte[] val = new byte[200]; proceed = false; region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL); region.put("key1", val); region.put("key2", val); LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true; final CacheObserver old = CacheObserverHolder.setInstance(new CacheObserverAdapter() { @Override public void afterSettingOplogOffSet(long offset) { ((LocalRegion) region).getDiskRegion().forceRolling(); // Let the operation thread yield to the Roller so that // it is able to obtain the iterator of the concurrrent region map // & thus get the reference to the entry which will contain // value as Token.Removed as the entry though removed from // concurrent // map still will be available to the roller Thread.yield(); // Sleep for some time try { Thread.sleep(5000); } catch (InterruptedException e) { testFailed = true; failureCause = "No guarantee that test is succesful"; fail("No guarantee that test is succesful"); } } @Override public void afterHavingCompacted() { proceed = true; synchronized (OplogJUnitTest.this) { OplogJUnitTest.this.notify(); } } }); try { region.destroy("key1"); region.destroy("key2"); } catch (Exception e1) { LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false; CacheObserverHolder.setInstance(old); fail("Test failed as entry deletion threw exception. Exception = " + e1); } // Wait for some time & check if the after having rolled callabck // is issued sucessfully or not. if (!proceed) { synchronized (this) { if (!proceed) { try { this.wait(20000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // The test will automatically fail due to proceed flag } } } } assertFalse(failureCause, testFailed); LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false; CacheObserverHolder.setInstance(old); if (!proceed) { fail("Test failed as afterHavingCompacted callabck not issued even after sufficient wait"); } closeDown(); }