/** * The implementation for getPackets() function. This is a blocking API. * * @param sessionid * @return A list of packets associated with the session */ @Override public List<ByteBuffer> getPackets(String sessionid) throws org.apache.thrift.TException { List<ByteBuffer> packets = new ArrayList<ByteBuffer>(); int count = 0; while (!msgQueues.containsKey(sessionid) && count++ < 100) { log.debug("Queue for session {} doesn't exist yet.", sessionid); try { Thread.sleep(100); // Wait 100 ms to check again. } catch (InterruptedException e) { log.error(e.toString()); } } if (count < 100) { SessionQueue pQueue = msgQueues.get(sessionid); BlockingQueue<ByteBuffer> queue = pQueue.getQueue(); // Block if queue is empty try { packets.add(queue.take()); queue.drainTo(packets); } catch (InterruptedException e) { log.error(e.toString()); } } return packets; }
public int computeStep(int metric) { int work = 0; if (nSteps == whenToThrow) { throw new ExpectedRuntimeException("Hash step throw test"); } if (nSteps-- > 0) { if (eachStepTime > 0) { Deadline time = Deadline.in(eachStepTime); while (!time.expired()) { try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e.toString()); } work++; } } else { work = -eachStepTime; TimeBase.step(work); try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e.toString()); } } } return work; }
public static void main(String[] args) throws LBMException { LBMContext ctx = null; /* Context object: container for UM "instance". */ LBMSource src = null; /* Source object: for sending messages. */ SrcCB srccb = new SrcCB(); /** * Initialization: create necessary UM objects. ** */ try { LBMTopic topic = null; LBMSourceAttributes srcAttr = null; ctx = new LBMContext(); srcAttr = new LBMSourceAttributes(); srcAttr.setValue("ume_store", "127.0.0.1:29999"); srcAttr.setValue("ume_store_behavior", "qc"); topic = ctx.allocTopic("test.topic", srcAttr); src = ctx.createSource(topic, srccb, null, null); } catch (LBMException ex) { System.err.println("Error initializing LBM objects: " + ex.toString()); System.exit(1); } while (true) { if (srcReady == 1) { /** * Send a message. ** */ try { src.send("test".getBytes(), "test".getBytes().length, LBM.MSG_FLUSH | LBM.SRC_NONBLOCK); } catch (LBMException ex) { /* Error trying to send, wait 1 second and try again */ try { Thread.sleep(1000); } catch (InterruptedException tex) { System.err.println("Error Thread.sleep interrupted: " + tex.toString()); System.exit(1); } } } else { /* No quorum, wait 1 second and check again */ System.out.println("Source is not ready to send (no quorum)"); try { Thread.sleep(1000); } catch (InterruptedException tex) { System.err.println("Error Thread.sleep interrupted: " + tex.toString()); System.exit(1); } } } } /* main */
public void run() { for (int i = 0; i < mMaxIterations; i++) try { if (Thread.interrupted()) { throw new InterruptedException(); } Integer result = (Integer) mQueue.take(); System.out.println("iteration = " + result); } catch (InterruptedException e) { System.out.println( "Thread properly interrupted by " + e.toString() + " in consumerRunnable"); // This isn't an error - it just means that // we've been interrupted by the main Thread. return; } catch (TimeoutException e) { System.out.println("Exception " + e.toString() + " occurred in consumerRunnable"); // Indicate a timeout. mConsumerCounter = TIMEOUT_OCCURRED; return; } catch (Exception e) { System.out.println("Exception " + e.toString() + " occurred in consumerRunnable"); // Indicate a failure. mConsumerCounter = FAILURE_OCCURRED; return; } }
/** * If this session is not connected, this method returns; otherwise this method sends a * LOGOUT_REQUEST to the server, and waits for this client to receive a LOGOUT_SUCCESS * acknowledgment or the timeout to expire, whichever comes first. If the LOGOUT_SUCCESS * acknowledgment is not received, then {@code AssertionFailedError} is thrown. */ public void logout() { synchronized (lock) { if (connected == false) { return; } logoutAck = false; } MessageBuffer buf = new MessageBuffer(1); buf.putByte(SimpleSgsProtocol.LOGOUT_REQUEST); try { connection.sendBytes(buf.getBuffer()); } catch (IOException e) { throw new RuntimeException(e); } synchronized (lock) { try { if (logoutAck == false) { lock.wait(WAIT_TIME); } if (logoutAck != true) { fail(toString() + " logout timed out"); } } catch (InterruptedException e) { fail(toString() + " logout timed out: " + e.toString()); } finally { if (!logoutAck) disconnect(); } } }
/** * openConnections: open the connection to the master. has retry mechanism * * @return: true if the connection is built, false if failed */ public boolean openConnections() { _log("Try to connect to Master..."); int i = 0; while (true) { boolean isConnected = connect(); if (!isConnected) { i++; if (i == DropboxConstants.MAX_TRY) { break; } _log("Cannot connect to Master, retry " + i); try { Thread.sleep(DropboxConstants.TRY_CONNECT_MILLIS); } catch (InterruptedException e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } _log("Retry connection is interrupted"); break; } } else { _log("Success!"); return true; } } _log("Failed"); return false; }
private static void doSleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException("Interrupted: " + e.toString()); } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { String noteId = context.getJobDetail().getJobDataMap().getString("noteId"); Note note = notebook.getNote(noteId); note.runAll(); while (!note.isTerminated()) { try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.toString(), e); } } boolean releaseResource = false; try { Map<String, Object> config = note.getConfig(); if (config != null && config.containsKey("releaseresource")) { releaseResource = (boolean) note.getConfig().get("releaseresource"); } } catch (ClassCastException e) { logger.error(e.getMessage(), e); } if (releaseResource) { for (InterpreterSetting setting : notebook.getInterpreterFactory().getInterpreterSettings(note.getId())) { notebook.getInterpreterFactory().restart(setting.getId()); } } }
public static void main(String[] args) { long head = 0; num_thread = Integer.parseInt(args[0]); long total = Long.parseLong(args[1]); section = total / ((long) num_thread); sectionHead = new long[num_thread]; long start = System.currentTimeMillis(); Thread[] threads = new Thread[num_thread]; for (int i = 0; i < num_thread; i++) { threads[i] = new Thread(new CoinFlip(i)); threads[i].start(); } for (int j = 0; j < num_thread; j++) { try { threads[j].join(); head = head + sectionHead[j]; } catch (InterruptedException e) { System.out.println( "Thread interrupted. Exception: " + e.toString() + " Message: " + e.getMessage()); return; } } long end = System.currentTimeMillis(); System.out.println(head + " heads in " + args[1] + " coin tosses"); System.out.println("Elapsed time: " + ((end - start)) + "ms"); }
// The method executing the task @Override public void execute() throws BuildException { this.log("Starting PlantUML"); try { if (dir != null) { final File error = processingSingleDirectory(new File(dir)); eventuallyFailfast(error); } for (FileSet fileSet : filesets) { final File error = manageFileSet(fileSet); eventuallyFailfast(error); } for (FileList fileList : filelists) { final File error = manageFileList(fileList); eventuallyFailfast(error); } if (executorService != null) { executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } this.log("Nb images generated: " + nbFiles.get()); } catch (IOException e) { e.printStackTrace(); throw new BuildException(e.toString()); } catch (InterruptedException e) { e.printStackTrace(); throw new BuildException(e.toString()); } }
/* * Called when a connector is doing reconnection. Like <code>postReconnection</code>, * this method is intended to be called only by a client connector: * <code>RMIConnector</code> and <code>ClientIntermediary</code>. * Call this method will set the flag beingReconnection to <code>true</code>, * and the thread used to fetch notifis will be stopped, a new thread can be * created only after the method <code>postReconnection</code> is called. * * It is caller's responsiblity to not re-call this method before calling * <code>postReconnection</code>. */ public synchronized ClientListenerInfo[] preReconnection() throws IOException { if (state == TERMINATED || beingReconnected) { // should never throw new IOException("Illegal state."); } final ClientListenerInfo[] tmp = infoList.values().toArray(new ClientListenerInfo[0]); beingReconnected = true; infoList.clear(); if (currentFetchThread == Thread.currentThread()) { /* we do not need to stop the fetching thread, because this thread is used to do restarting and it will not be used to do fetching during the re-registering the listeners.*/ return tmp; } while (state == STARTING) { try { wait(); } catch (InterruptedException ire) { IOException ioe = new IOException(ire.toString()); EnvHelp.initCause(ioe, ire); throw ioe; } } if (state == STARTED) { setState(STOPPING); } return tmp; }
protected void createPDFFile() throws CreatePDFFileException { String cmdLine = null; try { File newPdfFile = new File(_workingDir + File.separator + _localFilename + EXTENTION); if (Registry.isCommandLineMode()) { handleMultipleDocuments(newPdfFile); } cmdLine = createC42PDFCommandLine(newPdfFile.getName()); if (log.isDebugEnabled()) { log.debug("Running " + cmdLine); } // run C42PDF to create the file & wait till it finishes. Process p = Runtime.getRuntime().exec(cmdLine); p.waitFor(); // check to see if it worked if (!newPdfFile.exists()) { log.warn("PDF File was not created!"); throw new CreatePDFFileException("PDF File was not created!"); } } catch (IOException e) { e.printStackTrace(); throw new CreatePDFFileException(e.toString()); } catch (InterruptedException e) { e.printStackTrace(); throw new CreatePDFFileException(e.toString()); } return; }
/** * Wipe the device. * * @param code - Operation code. * @param data - Data required by the operation(PIN). */ public void wipeDevice(String code, String data) { String inputPin; String savedPin = Preference.getString(context, resources.getString(R.string.shared_pref_pin)); try { JSONObject wipeKey = new JSONObject(data); inputPin = (String) wipeKey.get(resources.getString(R.string.shared_pref_pin)); String status; if (inputPin.trim().equals(savedPin.trim())) { status = resources.getString(R.string.shared_pref_default_status); } else { status = resources.getString(R.string.shared_pref_false_status); } resultBuilder.build(code, status); if (inputPin.trim().equals(savedPin.trim())) { Toast.makeText(context, resources.getString(R.string.toast_message_wipe), Toast.LENGTH_LONG) .show(); try { Thread.sleep(PRE_WIPE_WAIT_TIME); } catch (InterruptedException e) { Log.e(TAG, "Wipe pause interrupted :" + e.toString()); } devicePolicyManager.wipeData(ACTIVATION_REQUEST); } else { Toast.makeText( context, resources.getString(R.string.toast_message_wipe_failed), Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Log.e(TAG, "Invalid JSON format." + e); } }
private boolean waitForAvailableConnection(long expireTime) { _availableWaitCount.incrementAndGet(); try { synchronized (_availableLock) { // return false only if the timeout occurs before the wait boolean isAfterWait = false; while (!isIdleAvailable() && !isCreateAvailable()) { try { long now = CurrentTime.getCurrentTimeActual(); long delta = expireTime - now; if (delta <= 0) return isAfterWait; Thread.interrupted(); _availableLock.wait(delta); isAfterWait = true; } catch (InterruptedException e) { log.log(Level.FINER, e.toString(), e); } } return true; } } finally { _availableWaitCount.decrementAndGet(); } }
public void showProgress() { for (int i = 0; i <= 100; i++) { try { Thread.sleep(100); pb.setValue(i); if (pb.getValue() == 50) // se il progresso è alla metà creiamo un progress monitor { pm = new ProgressMonitor(this, "...sto computando...", null, 0, 5); for (int x = 0; x <= 5; x++) { Thread.sleep(1000); pm.setProgress(x); } // crea un progress monitor per la lettura di dati da un file File a_f = new File(getClass().getResource("SomeText.txt").getPath()); try (FileInputStream fileIn = new FileInputStream(a_f); ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(this, "Reading SomeText.txt", fileIn); Scanner in = new Scanner(pmis)) { while (in.hasNextLine()) { String line = in.nextLine(); Thread.sleep(10); } } catch (IOException ioe) { JOptionPane.showMessageDialog(this, ioe.toString()); } } } catch (InterruptedException ie) { JOptionPane.showMessageDialog(this, ie.toString()); } } }
public static void sleep(long ms) { // TODO 添加出错处理 try { Thread.sleep(ms); } catch (InterruptedException e) { Logger.e(TAG, "Sleep failed: " + e.toString()); } }
/** * Sets up the fixture, for example, open a network connection. This method is called before a * test is executed. */ protected void startClient(int port) { t = new Thread(new SSClient(port), "SSClient"); t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Exception during startClinet()" + e.toString()); } }
/** * Active scan of all pages found at given url. * * @param url the url for active scan * @throws ClientApiException */ private void activeScan(String url) throws ClientApiException { clientApi.ascan.scan(apiKey, url, "true", "false"); while (statusToInt(clientApi.ascan.status()) < 100) { try { Thread.sleep(500); } catch (InterruptedException e) { getLog().error(e.toString()); } } }
public void run() { try { for (int i = 1; i <= REPETITIONS; i++) { System.out.println("deposite " + i); bm.deposit((double) i); Thread.sleep(DELAY); } } catch (InterruptedException exception) { // throw from exception System.out.println(exception.toString()); } }
/** * Search for all links and pages on the URL * * @param url the to investigate URL * @throws ClientApiException */ private void spider(String url) throws ClientApiException { clientApi.spider.scan(apiKey, url); while (statusToInt(clientApi.spider.status()) < 100) { try { Thread.sleep(500); } catch (InterruptedException e) { getLog().error(e.toString()); } } }
public void Close() { final String methodName = "Close"; Logfile.WriteCalled(logLevel, STR_ClassName, methodName); try { if (this.labExperimentEngines == null) { throw new NullPointerException(STRERR_LabExperimentEngines); } /* * Check each experiment engine to see if it is running an experiment */ for (int unitId = 0; unitId < this.labManagement.getFarmSize(); unitId++) { /* * Get the experiment engine */ LabExperimentEngine labExperimentEngine = this.labExperimentEngines[unitId]; if (labExperimentEngine == null) { throw new NullPointerException( String.format(STRERR_LabExperimentEngineUnitId_arg, unitId)); } /* * Shutdown experiment engine */ labExperimentEngine.Close(); } } catch (Exception ex) { Logfile.WriteError(ex.toString()); } /* * Shutdown experiment manager */ if (this.running == true) { this.stopRunning = true; /* * Lab experiment manager thread may be waiting for an experiment submission signal */ this.labManagement.getSignalSubmitted().Notify(); /* * Wait for LabExperimentManager thread to terminate */ try { this.thread.join(); } catch (InterruptedException ex) { Logfile.WriteError(ex.toString()); } } Logfile.WriteCompleted(logLevel, STR_ClassName, methodName); }
/** @see WebApplicationProxy#stop() */ public void doStop() { try { scanFiles = null; TaskLog.logWithTimestamp("Stopping web application " + this); Thread.currentThread().sleep(500L); super.doStop(); } catch (InterruptedException e) { TaskLog.log(e.toString()); } catch (Exception e) { TaskLog.log(e.toString()); } }
/** listen: start to listen if there is any clients connected */ public void listen() { // Firstly spawn a new thread and then the main thread // also start listening _userNet = new DropboxFileServerUserNet(_server, _userOut, _userIn, _userSock); _userNet.start(); /* Use main thread, cannot be stopped */ while (_sock != null && !_sock.isClosed()) { try { String line = NetComm.receive(_in); _dlog(line); parse(line); } catch (Exception e) { if (!_server.noException()) { _elog(e.toString()); } break; // Break the loop } } /* Clear */ // Close main thread clear(); // Cancel the listening thread and retry _server.cancelListeningThread(); /* Also cancel all of the syncers */ _server.cancelSyncers(); // Retry after try { _log( "The connection to master is broken," + " reset everything and retry connection after " + DropboxConstants.TRY_CONNECT_MILLIS + " milliseconds"); Thread.sleep(DropboxConstants.TRY_CONNECT_MILLIS); } catch (InterruptedException e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } } _server.run(); clear(); _log(_threadName + " is stopped"); }
// the method which actually copies the caches locally and unjars/unzips them // and does chmod for the files private static Path localizeCache( Configuration conf, URI cache, long confFileStamp, CacheStatus cacheStatus, boolean isArchive) throws IOException { FileSystem fs = getFileSystem(cache, conf); FileSystem localFs = FileSystem.getLocal(conf); Path parchive = null; if (isArchive) { parchive = new Path( cacheStatus.localizedLoadPath, new Path(cacheStatus.localizedLoadPath.getName())); } else { parchive = cacheStatus.localizedLoadPath; } if (!localFs.mkdirs(parchive.getParent())) { throw new IOException( "Mkdirs failed to create directory " + cacheStatus.localizedLoadPath.toString()); } String cacheId = cache.getPath(); fs.copyToLocalFile(new Path(cacheId), parchive); if (isArchive) { String tmpArchive = parchive.toString().toLowerCase(); File srcFile = new File(parchive.toString()); File destDir = new File(parchive.getParent().toString()); if (tmpArchive.endsWith(".jar")) { RunJar.unJar(srcFile, destDir); } else if (tmpArchive.endsWith(".zip")) { FileUtil.unZip(srcFile, destDir); } else if (isTarFile(tmpArchive)) { FileUtil.unTar(srcFile, destDir); } // else will not do anyhting // and copy the file into the dir as it is } long cacheSize = FileUtil.getDU(new File(parchive.getParent().toString())); cacheStatus.size = cacheSize; addCacheInfoUpdate(cacheStatus); // do chmod here try { // Setting recursive permission to grant everyone read and execute Path localDir = new Path(cacheStatus.localizedBaseDir, cacheStatus.uniqueParentDir); LOG.info("Doing chmod on localdir :" + localDir); FileUtil.chmod(localDir.toString(), "ugo+rx", true); } catch (InterruptedException e) { LOG.warn("Exception in chmod" + e.toString()); } // update cacheStatus to reflect the newly cached file cacheStatus.mtime = getTimestamp(conf, cache); return cacheStatus.localizedLoadPath; }
/** * Called after reconnection is finished. This method is intended to be called only by a client * connector: <code>RMIConnector</code> and <code>ClientIntermediary</code>. */ public synchronized void postReconnection(ClientListenerInfo[] listenerInfos) throws IOException { if (state == TERMINATED) { return; } while (state == STOPPING) { try { wait(); } catch (InterruptedException ire) { IOException ioe = new IOException(ire.toString()); EnvHelp.initCause(ioe, ire); throw ioe; } } final boolean trace = logger.traceOn(); final int len = listenerInfos.length; for (int i = 0; i < len; i++) { if (trace) { logger.trace( "addNotificationListeners", "Add a listener at " + listenerInfos[i].getListenerID()); } infoList.put(listenerInfos[i].getListenerID(), listenerInfos[i]); } beingReconnected = false; notifyAll(); if (currentFetchThread == Thread.currentThread()) { // no need to init, simply get the id try { mbeanRemovedNotifID = addListenerForMBeanRemovedNotif(); } catch (Exception e) { final String msg = "Failed to register a listener to the mbean " + "server: the client will not do clean when an MBean " + "is unregistered"; if (logger.traceOn()) { logger.trace("init", msg, e); } } } else if (listenerInfos.length > 0) { // old listeners re-registered init(true); } else if (infoList.size() > 0) { // but new listeners registered during reconnection init(false); } }
public void run() { Log.w(TAG, "Update thread started"); Running = true; while (!Thread.currentThread().isInterrupted() && Running) { try { Thread.sleep(DELAY); update(); } catch (InterruptedException e) { Log.w(TAG, "Registry update thread caught exception: " + e.toString()); Running = false; } } Log.w(TAG, "Update thread stopping..."); }
public static void stop() { _bLogging = false; synchronized (lock) { lock.notifyAll(); } while (_bRunning) { try { Thread.sleep(100); } catch (InterruptedException e) { Logger.e(TAG, e.toString()); } } _closeLogFile(); }
/** The task runs as a thread. */ @Override public void run() { try { Thread.sleep(1500); } catch (final InterruptedException e) { LOG.log(Level.SEVERE, e.toString(), e); } if (networkService.isNetworkUp()) { chatState.setLogonCompleted(true); // To stop the timer from running in the background cancel(); } }
public static void main(String[] args) throws UnknownHostException { long rows = 0; long start = System.currentTimeMillis(); if (args.length < 4) { usage(1); } String operation = args[0]; rows = Long.parseLong(args[1]); // 需要测试插入的条数 int tnum = Integer.parseInt(args[2]); long batchnum = Long.parseLong(args[3]); String host = "172.17.0.9"; // 由于采用shard,需要直接连接 mongos路由服务器地址 String dbname = "rtm"; // 数据库名称 MongoDb[] mongothread = new MongoDb[tnum]; for (int k = 0; k < tnum; k++) { mongothread[k] = new MongoDb(operation, rows, host, dbname, batchnum, k); mongothread[k].start(); } // 确保所有进程都已经完成后 进入下面的 sysout输出模块 for (int k = 0; k < tnum; k++) { // System.out.println("mongothread["+k+"].isAlive()=" + // mongothread[k].isAlive()); if (mongothread[k].isAlive()) { try { mongothread[k].join(); } catch (InterruptedException ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } long stop = System.currentTimeMillis(); long endtime = (stop - start) / 1000; if (endtime == 0) endtime = 1; long result = rows / endtime; long tresult = rows * tnum / endtime; System.out.print("Total thread:" + tnum + "\n"); System.out.print("Total run time:" + endtime + " sec\n"); System.out.print("Per-thread rows:" + rows + "\n"); System.out.print("Per-thread " + "mongo" + " " + operation + " Result:" + result + "row/sec\n"); System.out.print("Total-thread rows:" + rows * tnum + "\n"); System.out.print( "Total-thread " + "mongo" + " " + operation + " Result:" + tresult + "row/sec\n"); }
public void run() { Activity activity = getConfig().getController().getActivity(); mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL); while (isActive()) { try { Thread.sleep(samplingRate); getLastKnownData(); } catch (InterruptedException e) { Log.e(e.getMessage(), e.toString()); } } }