List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:com.chen.emailsync.SyncManager.java
public void stopAccountSyncs(long acctId, boolean includeAccountMailbox) { synchronized (sSyncLock) { List<Long> deletedBoxes = new ArrayList<Long>(); for (Long mid : mServiceMap.keySet()) { Mailbox box = Mailbox.restoreMailboxWithId(this, mid); if (box != null) { if (box.mAccountKey == acctId) { if (!includeAccountMailbox && box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { AbstractSyncService svc = mServiceMap.get(mid); if (svc != null) { svc.stop();// w ww . j a v a 2 s .c o m } continue; } AbstractSyncService svc = mServiceMap.get(mid); if (svc != null) { svc.stop(); Thread t = svc.mThread; if (t != null) { t.interrupt(); } } deletedBoxes.add(mid); } } } for (Long mid : deletedBoxes) { releaseMailbox(mid); } } }
From source file:edu.harvard.i2b2.pm.ws.PMService.java
/** * This function is main webservice interface to get pulmonary data from * pulmonary report. It uses AXIOM elements(OMElement) to conveniently parse * xml messages.//from ww w . j a va 2s. c o m * * It excepts incoming request in i2b2 message format, which wraps PFT * report inside patientdata object. The response is also will be in i2b2 * message, which will wrap patientdata object. Patient data object will * have all the extracted pft concepts from the report. * * * @param getServices * @return OMElement in i2b2message format * @throws PortletServiceNotFoundException * @throws PortletServiceUnavailableException * @throws Exception */ public OMElement getServices(OMElement getPMDataElement) throws I2B2Exception { /* OMElement returnElement = null; String pmDataResponse = null; String unknownErrorMessage = "Error message delivered from the remote server \n" + "You may wish to retry your last action"; if (getPMDataElement == null) { log.error("Incoming PM request is null"); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); return MessageFactory.createResponseOMElementFromString(pmDataResponse); } ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); // String requestElementString = getPMDataElement.toString(); // childrenDataMsg.setRequestMessageType(requestElementString); long waitTime = 0; if (servicesMsg.getRequestMessageType() != null) { if (servicesMsg.getRequestMessageType().getRequestHeader() != null) { waitTime = servicesMsg.getRequestMessageType() .getRequestHeader() .getResultWaittimeMs(); } } //do Workplace query processing inside thread, so that // service could send back message with timeout error. ExecutorRunnable er = new ExecutorRunnable(); return er.execute(new ServicesHandler(servicesMsg), waitTime); */ OMElement returnElement = null; if (getPMDataElement == null) { log.error("Incoming PM request is null"); throw new I2B2Exception("Incoming PM request is null"); } Pattern p = Pattern.compile("<password>.+</password>"); Matcher m = p.matcher(getPMDataElement.toString()); String outString = m.replaceAll("<password>*********</password>"); p = Pattern.compile(">.+</ns9:set_password>"); m = p.matcher(outString); outString = m.replaceAll(">*********</ns9:set_password>"); log.debug("Received Request PM Element " + outString); log.debug("Begin getting servicesMsg"); ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); long waitTime = 0; if (servicesMsg.getRequestMessageType() != null) { if (servicesMsg.getRequestMessageType().getRequestHeader() != null) { waitTime = servicesMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); } } log.debug("Completed getting servicesMsg, waittime is: " + waitTime); //do PM processing inside thread, so that // service could sends back message with timeout error. String pmDataResponse = null; try { ExecutorRunnable er = new ExecutorRunnable(); //er.setInputString(requestElementString); log.debug("begin setRequestHandler, my servicesMsg: " + servicesMsg); er.setRequestHandler(new ServicesHandler(servicesMsg)); log.debug("middle setRequestHandler"); log.debug("end setRequestHandler"); Thread t = new Thread(er); ResponseMessageType responseMsgType = null; synchronized (t) { t.start(); try { //if (waitTime > 0) { // t.wait(waitTime); //} else { // t.wait(); //} long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { t.wait(); } } pmDataResponse = er.getOutputString(); if (pmDataResponse == null) { if (er.getJobException() != null) { pmDataResponse = ""; throw new I2B2Exception("Portal is not property configured."); } else if (er.isJobCompleteFlag() == false) { String timeOuterror = "Result waittime millisecond <result_waittime_ms> :" + waitTime + " elapsed, try again with increased value"; log.debug(timeOuterror); responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); } } } catch (InterruptedException e) { log.error("Error in thread: " + e.getMessage()); e.printStackTrace(); throw new I2B2Exception("Thread error while running PM job " + getPMDataElement, e); } finally { t.interrupt(); er = null; t = null; } } } catch (Exception e) { log.error("Error: " + e.getMessage()); e.printStackTrace(); } try { returnElement = MessageFactory.createResponseOMElementFromString(pmDataResponse); log.debug("my pm repsonse is: " + pmDataResponse); log.debug("my return is: " + returnElement); } catch (XMLStreamException e) { log.error("Error creating OMElement from response string " + pmDataResponse, e); } return returnElement; }
From source file:org.apache.bookkeeper.benchmark.BenchThroughputLatency.java
public void run() { LOG.info("Running..."); long start = previous = System.currentTimeMillis(); int sent = 0; Thread reporter = new Thread() { public void run() { try { while (true) { Thread.sleep(1000); LOG.info("ms: {} req: {}", System.currentTimeMillis(), completedRequests.getAndSet(0)); }// w w w . jav a 2 s . co m } catch (InterruptedException ie) { LOG.info("Caught interrupted exception, going away"); } } }; reporter.start(); long beforeSend = System.nanoTime(); while (!Thread.currentThread().isInterrupted() && sent < sendLimit) { try { sem.acquire(); if (sent == 10000) { long afterSend = System.nanoTime(); long time = afterSend - beforeSend; LOG.info("Time to send first batch: {}s {}ns ", time / 1000 / 1000 / 1000, time); } } catch (InterruptedException e) { break; } final int index = getRandomLedger(); LedgerHandle h = lh[index]; if (h == null) { LOG.error("Handle " + index + " is null!"); } else { long nanoTime = System.nanoTime(); lh[index].asyncAddEntry(bytes, this, new Context(sent, nanoTime)); counter.incrementAndGet(); } sent++; } LOG.info("Sent: " + sent); try { int i = 0; while (this.counter.get() > 0) { Thread.sleep(1000); i++; if (i > 30) { break; } } } catch (InterruptedException e) { LOG.error("Interrupted while waiting", e); } synchronized (this) { duration = System.currentTimeMillis() - start; } throughput = sent * 1000 / getDuration(); reporter.interrupt(); try { reporter.join(); } catch (InterruptedException ie) { // ignore } LOG.info("Finished processing in ms: " + getDuration() + " tp = " + throughput); }
From source file:edu.wisc.commons.httpclient.CleanShutdownPoolingClientConnectionManager.java
@Override public void shutdown() { if (shutdownComplete.get() || !this.shutdownLock.tryLock()) { //Already shutdown or shutdown in progress return;// w w w . j a va2 s . co m } try { //Create Thread to call shutdown final Thread shutdownThread = new Thread(new Runnable() { @Override public void run() { try { logger.info("PoolingClientConnectionManager shutdown started"); CleanShutdownPoolingClientConnectionManager.super.shutdown(); } finally { shutdownComplete.set(true); logger.info("PoolingClientConnectionManager shutdown complete"); } } }); shutdownThread.setName("PoolingClientConnectionManager Shutdown Monitor"); shutdownThread.setDaemon(true); //start shutdown thread shutdownThread.start(); //track initial shutdown start time and time spent by the shutdown thread waiting or blocked final long shutdownStart = System.nanoTime(); long waitStart = shutdownStart; //Monitor the shutdown thread while (!shutdownComplete.get()) { final long now = System.nanoTime(); final long shutdownTime = TimeUnit.NANOSECONDS.toMillis(now - shutdownStart); //if time spent shutting down is greater than kill time forcibly stop the shutdown thread if (shutdownTime > this.shutdownThreadKillTime) { final String stackTrace = getStackTrace(shutdownThread); logger.error("Shutdown thread " + shutdownThread.getName() + " has been stopping for " + shutdownTime + "ms, killing it. THIS IS BAD. \n" + stackTrace); shutdownThread.stop(); //break out of the monitoring loop break; } //if time spent shutting down is greater than max time immediately interrupt the thread else if (shutdownTime > this.shutdownThreadMaxTime) { logger.warn("Shutdown thread " + shutdownThread.getName() + " has been stopping for " + shutdownTime + "ms, interrupting immediately"); shutdownThread.interrupt(); } //otherwise check the state of the thread else { //If the thread is blocked or waiting and has been for longer than the max wait time //interrupt the thread. If not in blocked or waiting state update the wait-start time final State state = shutdownThread.getState(); switch (state) { case BLOCKED: case TIMED_WAITING: case WAITING: { final long waitTime = TimeUnit.NANOSECONDS.toMillis(now - waitStart); if (waitTime > shutdownThreadMaxWaitTime) { logger.info("Shutdown thread " + shutdownThread.getName() + " has been waiting for " + waitTime + "ms, interrupting"); shutdownThread.interrupt(); } else { break; } } default: { waitStart = now; break; } } } //Sleep between state checks, don't want to overload anything try { Thread.sleep(shutdownThreadPollRate); } catch (InterruptedException e) { //ignore } } } finally { this.shutdownLock.unlock(); } }
From source file:org.red5.net.websocket.WebSocketServerTest.java
@SuppressWarnings("unused") @Test/*from w ww . j a v a 2 s . c o m*/ public void testMultiThreaded() throws Throwable { log.info("testMultiThreaded enter"); // create the server instance Thread server = new Thread() { @Override public void run() { log.debug("Server thread run"); try { WSServer.main(null); } catch (Exception e) { log.error("Error in server thread", e); } log.debug("Server thread exit"); } }; server.setDaemon(true); server.start(); // add plugin to the registry WebSocketPlugin plugin = new WebSocketPlugin(); PluginRegistry.register(plugin); // start plugin plugin.doStart(); // create a scope for the manager IScope appScope = new GlobalScope(); // create an app MultiThreadedApplicationAdapter app = new MultiThreadedApplicationAdapter(); app.setScope(appScope); // add the app plugin.setApplication(app); // get the manager WebSocketScopeManager manager = plugin.getManager(appScope); manager.setApplication(appScope); // wait for server while (!WSServer.isListening()) { Thread.sleep(10L); } // how many threads int threads = 1; List<Worker> tasks = new ArrayList<Worker>(threads); for (int t = 0; t < threads; t++) { tasks.add(new Worker()); } ExecutorService executorService = Executors.newFixedThreadPool(threads); // invokeAll() blocks until all tasks have run... long start = System.nanoTime(); List<Future<Object>> futures = executorService.invokeAll(tasks); log.info("Runtime: {} ns", (System.nanoTime() - start)); for (Worker r : tasks) { // loop through and check results } Thread.sleep(2000L); // stop server server.interrupt(); WSServer.stop(); // stop plugin PluginRegistry.shutdown(); log.info("testMultiThreaded exit"); }
From source file:org.kalypso.util.net.URLGetter.java
/** * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor) *///from w ww. j av a2 s. c o m @Override public IStatus execute(final IProgressMonitor monitor) { final String urlAsString = m_url.toString(); final HttpMethod method = new GetMethod(urlAsString); // do not forget the next line! method.setDoAuthentication(true); final Thread thread = new Thread() { @Override public void run() { try { final HttpClient httpClient = getHttpClient(); httpClient.executeMethod(method); setResult(method.getResponseBodyAsStream()); } catch (final IOException e) { final IStatus status; String responseBodyAsString = Messages.getString("org.kalypso.util.net.URLGetter.1"); //$NON-NLS-1$ try { responseBodyAsString = method.getResponseBodyAsString(); } catch (final IOException e1) { final IStatus status2 = StatusUtilities.statusFromThrowable(e1); KalypsoGisPlugin.getDefault().getLog().log(status2); } String message = Messages.getString("org.kalypso.util.net.URLGetter.2") + urlAsString; //$NON-NLS-1$ if (responseBodyAsString != null && !responseBodyAsString.isEmpty()) message += "\n" + responseBodyAsString; //$NON-NLS-1$ status = new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), 0, message, e); setStatus(status); } } }; monitor.beginTask(urlAsString, IProgressMonitor.UNKNOWN); monitor.subTask(Messages.getString("org.kalypso.util.net.URLGetter.4")); //$NON-NLS-1$ thread.start(); while (thread.isAlive()) { try { Thread.sleep(100); } catch (final InterruptedException e1) { // should never happen, ignore e1.printStackTrace(); } final String statusText; final StatusLine statusLine = method.getStatusLine(); if (statusLine == null) statusText = Messages.getString("org.kalypso.util.net.URLGetter.5"); //$NON-NLS-1$ else statusText = method.getStatusText(); monitor.subTask(statusText); monitor.worked(1); if (monitor.isCanceled()) { // TODO: this does not stop the thread! thread.interrupt(); monitor.done(); return Status.CANCEL_STATUS; } } monitor.done(); return m_status; }
From source file:backup.integration.MiniClusterTestBase.java
@Test public void testIntegrationBasic() throws Exception { File hdfsDir = setupHdfsLocalDir(); Configuration conf = setupConfig(hdfsDir); MiniDFSCluster hdfsCluster = new MiniDFSCluster.Builder(conf).build(); Thread thread = null; try {//from w w w . j av a 2 s .c o m DistributedFileSystem fileSystem = hdfsCluster.getFileSystem(); Path path = new Path("/testing.txt"); writeFile(fileSystem, path); Thread.sleep(TimeUnit.SECONDS.toMillis(5)); AtomicBoolean success = new AtomicBoolean(false); thread = new Thread(new Runnable() { @Override public void run() { boolean beginTest = true; while (true) { try { try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { try (FSDataInputStream inputStream = fileSystem.open(path)) { IOUtils.copy(inputStream, output); } if (beginTest) { hdfsCluster.startDataNodes(conf, 1, true, null, null); hdfsCluster.stopDataNode(0); beginTest = false; } else { LOG.info("Missing block restored."); success.set(true); return; } } } catch (IOException e) { LOG.error(e.getMessage()); } try { Thread.sleep(1000); } catch (InterruptedException e) { return; } } } }); thread.start(); thread.join(TimeUnit.MINUTES.toMillis(2)); if (!success.get()) { fail(); } } finally { if (thread != null) { thread.interrupt(); } hdfsCluster.shutdown(); destroyBackupStore(conf); } }
From source file:org.apache.hive.jdbc.TestJdbcDriver2.java
/** * Test getting query log method in Jdbc * @throws Exception/* w w w . ja v a 2 s. c om*/ */ @Test public void testGetQueryLog() throws Exception { // Prepare String[] expectedLogs = { "Parsing command", "Parse Completed", "Starting Semantic Analysis", "Semantic Analysis Completed", "Starting command" }; String sql = "select count(*) from " + tableName; // Verify the fetched log (from the beginning of log file) HiveStatement stmt = (HiveStatement) con.createStatement(); assertNotNull("Statement is null", stmt); stmt.executeQuery(sql); List<String> logs = stmt.getQueryLog(false, 10000); stmt.close(); verifyFetchedLog(logs, expectedLogs); // Verify the fetched log (incrementally) final HiveStatement statement = (HiveStatement) con.createStatement(); assertNotNull("Statement is null", statement); statement.setFetchSize(10000); final List<String> incrementalLogs = new ArrayList<String>(); Runnable logThread = new Runnable() { @Override public void run() { while (statement.hasMoreLogs()) { try { incrementalLogs.addAll(statement.getQueryLog()); Thread.sleep(500); } catch (SQLException e) { LOG.error("Failed getQueryLog. Error message: " + e.getMessage()); fail("error in getting log thread"); } catch (InterruptedException e) { LOG.error("Getting log thread is interrupted. Error message: " + e.getMessage()); fail("error in getting log thread"); } } } }; Thread thread = new Thread(logThread); thread.setDaemon(true); thread.start(); statement.executeQuery(sql); thread.interrupt(); thread.join(10000); // fetch remaining logs List<String> remainingLogs; do { remainingLogs = statement.getQueryLog(); incrementalLogs.addAll(remainingLogs); } while (remainingLogs.size() > 0); statement.close(); verifyFetchedLog(incrementalLogs, expectedLogs); }
From source file:org.apache.hadoop.hive.serde2.objectinspector.TestReflectionObjectInspectors.java
public void testObjectInspectorThreadSafety() throws InterruptedException { final int workerCount = 5; // 5 workers to run getReflectionObjectInspector concurrently final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(workerCount); final MutableObject exception = new MutableObject(); Thread runner = new Thread(new Runnable() { @Override/*from w w w. j a va2 s . c o m*/ @SuppressWarnings("unchecked") public void run() { Future<ObjectInspector>[] results = (Future<ObjectInspector>[]) new Future[workerCount]; ObjectPair<Type, ObjectInspectorFactory.ObjectInspectorOptions>[] types = (ObjectPair<Type, ObjectInspectorFactory.ObjectInspectorOptions>[]) new ObjectPair[] { new ObjectPair<Type, ObjectInspectorFactory.ObjectInspectorOptions>(Complex.class, ObjectInspectorFactory.ObjectInspectorOptions.THRIFT), new ObjectPair<Type, ObjectInspectorFactory.ObjectInspectorOptions>(MyStruct.class, ObjectInspectorFactory.ObjectInspectorOptions.JAVA), }; try { for (int i = 0; i < 20; i++) { // repeat 20 times for (final ObjectPair<Type, ObjectInspectorFactory.ObjectInspectorOptions> t : types) { ObjectInspectorFactory.objectInspectorCache.clear(); for (int k = 0; k < workerCount; k++) { results[k] = executorService.schedule(new Callable<ObjectInspector>() { @Override public ObjectInspector call() throws Exception { return ObjectInspectorFactory.getReflectionObjectInspector(t.getFirst(), t.getSecond()); } }, 50, TimeUnit.MILLISECONDS); } ObjectInspector oi = results[0].get(); for (int k = 1; k < workerCount; k++) { assertEquals(oi, results[k].get()); } } } } catch (Throwable e) { exception.setValue(e); } } }); try { runner.start(); long endTime = System.currentTimeMillis() + 300000; // timeout in 5 minutes while (runner.isAlive()) { if (System.currentTimeMillis() > endTime) { runner.interrupt(); // Interrupt the runner thread fail("Timed out waiting for the runner to finish"); } runner.join(10000); } if (exception.getValue() != null) { fail("Got exception: " + exception.getValue()); } } finally { executorService.shutdownNow(); } }