List of usage examples for java.lang Thread interrupted
public static boolean interrupted()
From source file:at.bitfire.davdroid.syncadapter.CalendarSyncManager.java
@Override protected void downloadRemote() throws IOException, HttpException, DavException, CalendarStorageException { App.log.info("Downloading " + toDownload.size() + " events (" + MAX_MULTIGET + " at once)"); // download new/updated iCalendars from server for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]), MAX_MULTIGET)) {/*from w w w. j a v a 2 s. co m*/ if (Thread.interrupted()) return; App.log.info("Downloading " + StringUtils.join(bunch, ", ")); if (bunch.length == 1) { // only one contact, use GET DavResource remote = bunch[0]; ResponseBody body = remote.get("text/calendar"); // CalDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc4791#section-5.3.4] GetETag eTag = (GetETag) remote.properties.get(GetETag.NAME); if (eTag == null || StringUtils.isEmpty(eTag.eTag)) throw new DavException("Received CalDAV GET response without ETag for " + remote.location); Charset charset = Charsets.UTF_8; MediaType contentType = body.contentType(); if (contentType != null) charset = contentType.charset(Charsets.UTF_8); @Cleanup InputStream stream = body.byteStream(); processVEvent(remote.fileName(), eTag.eTag, stream, charset); } else { // multiple contacts, use multi-get List<HttpUrl> urls = new LinkedList<>(); for (DavResource remote : bunch) urls.add(remote.location); davCalendar().multiget(urls.toArray(new HttpUrl[urls.size()])); // process multiget results for (DavResource remote : davCollection.members) { String eTag; GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME); if (getETag != null) eTag = getETag.eTag; else throw new DavException("Received multi-get response without ETag"); Charset charset = Charsets.UTF_8; GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME); if (getContentType != null && getContentType.type != null) { MediaType type = MediaType.parse(getContentType.type); if (type != null) charset = type.charset(Charsets.UTF_8); } CalendarData calendarData = (CalendarData) remote.properties.get(CalendarData.NAME); if (calendarData == null || calendarData.iCalendar == null) throw new DavException("Received multi-get response without address data"); @Cleanup InputStream stream = new ByteArrayInputStream(calendarData.iCalendar.getBytes()); processVEvent(remote.fileName(), eTag, stream, charset); } } } }
From source file:org.factor45.jhcb.benchmark.ApacheBenchmark.java
@Override protected BatchResult runBatch() { final CountDownLatch latch = new CountDownLatch(this.threads); final Vector<ThreadResult> threadResults = new Vector<ThreadResult>(this.threads); long batchStart = System.nanoTime(); for (int i = 0; i < this.threads; i++) { this.executor.submit(new Runnable() { @Override// w w w .ja v a 2 s .co m public void run() { int successful = 0; long start = System.nanoTime(); for (int i = 0; i < requestsPerThreadPerBatch; i++) { HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); response.getEntity().consumeContent(); if (response.getStatusLine().getStatusCode() == 200) { successful++; } } catch (IOException e) { get.abort(); } } long totalTime = System.nanoTime() - start; threadResults.add(new ThreadResult(requestsPerThreadPerBatch, successful, totalTime)); latch.countDown(); } }); } try { latch.await(); } catch (InterruptedException e) { Thread.interrupted(); } long batchTotalTime = System.nanoTime() - batchStart; return new BatchResult(threadResults, batchTotalTime); }
From source file:ThreadPoolMain.java
private void runIt(Runnable r) { try {//from w w w . j ava 2 s . c o m r.run(); } catch (Exception runex) { System.err.println("Uncaught exception fell through from run()"); runex.printStackTrace(); } finally { Thread.interrupted(); } }
From source file:org.apache.sqoop.mapreduce.ProgressThread.java
public void run() { this.lastReportMillis = System.currentTimeMillis(); this.startTimeMillis = this.lastReportMillis; final long MAX_PROGRESS = this.maxProgressPeriod; final long REPORT_INTERVAL = this.reportInterval; final long SLEEP_INTERVAL = this.sleepInterval; // In a loop: // * Check that we haven't run for too long (maxProgressPeriod). // * If it's been a report interval since we last made progress, // make more. // * Sleep for a bit. // * If the parent thread has signaled for exit, do so. while (this.keepGoing) { long curTimeMillis = System.currentTimeMillis(); if (MAX_PROGRESS != 0 && curTimeMillis - this.startTimeMillis > MAX_PROGRESS) { this.keepGoing = false; log.info("Auto-progress thread exiting after " + MAX_PROGRESS + " ms."); break; }//from w w w . j a va 2 s. co m if (curTimeMillis - this.lastReportMillis > REPORT_INTERVAL) { // It's been a full report interval -- claim progress. log.debug("Auto-progress thread reporting progress"); this.context.progress(); this.lastReportMillis = curTimeMillis; } // Unless we got an interrupt while we were working, // sleep a bit before doing more work. if (!Thread.interrupted()) { try { Thread.sleep(SLEEP_INTERVAL); } catch (InterruptedException ie) { // we were notified on something; not necessarily an error. } } } log.info("Auto-progress thread is finished. keepGoing=" + this.keepGoing); }
From source file:org.apache.hadoop.cifs.mapred.ProgressThread.java
public void run() { this.lastReportMillis = System.currentTimeMillis(); this.startTimeMillis = this.lastReportMillis; final long MAX_PROGRESS = this.maxProgressPeriod; final long REPORT_INTERVAL = this.reportInterval; final long SLEEP_INTERVAL = this.sleepInterval; // In a loop: // * Check that we haven't run for too long (maxProgressPeriod). // * If it's been a report interval since we last made progress, // make more. // * Sleep for a bit. // * If the parent thread has signaled for exit, do so. while (this.keepGoing) { long curTimeMillis = System.currentTimeMillis(); if (MAX_PROGRESS != 0 && curTimeMillis - this.startTimeMillis > MAX_PROGRESS) { this.keepGoing = false; log.info("Auto-progress thread exiting after " + MAX_PROGRESS + " ms."); break; }/* w w w . j a v a 2s . co m*/ if (curTimeMillis - this.lastReportMillis > REPORT_INTERVAL) { // It's been a full report interval -- claim progress. log.debug("Auto-progress thread reporting progress"); this.context.progress(); this.lastReportMillis = curTimeMillis; } // Unless we got an interrupt while we were working, // sleep a bit before doing more work. if (!Thread.interrupted()) { try { Thread.sleep(SLEEP_INTERVAL); } catch (InterruptedException ie) { // we were notified on something; not necessarily an error. } } } log.info("Auto-progress thread is finished. keepGoing=" + this.keepGoing); }
From source file:org.apache.hadoop.util.zookeeper.ZooKeeperImpl.java
public void close() { try {/*from w w w. j a v a 2 s.co m*/ delegate.close(); } catch (InterruptedException e) { Thread.interrupted(); throw new RuntimeException(e); } }
From source file:com.granita.contacticloudsync.syncadapter.CalendarSyncManager.java
@Override protected void downloadRemote() throws IOException, HttpException, DavException, CalendarStorageException { log.info("Downloading " + toDownload.size() + " events (" + MAX_MULTIGET + " at once)"); // download new/updated iCalendars from server for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]), MAX_MULTIGET)) {/*from w ww . j ava 2 s . c o m*/ if (Thread.interrupted()) return; log.info("Downloading " + StringUtils.join(bunch, ", ")); if (bunch.length == 1) { // only one contact, use GET DavResource remote = bunch[0]; ResponseBody body = remote.get("text/calendar"); String eTag = ((GetETag) remote.properties.get(GetETag.NAME)).eTag; Charset charset = Charsets.UTF_8; MediaType contentType = body.contentType(); if (contentType != null) charset = contentType.charset(Charsets.UTF_8); @Cleanup InputStream stream = body.byteStream(); processVEvent(remote.fileName(), eTag, stream, charset); } else { // multiple contacts, use multi-get List<HttpUrl> urls = new LinkedList<>(); for (DavResource remote : bunch) urls.add(remote.location); davCalendar().multiget(urls.toArray(new HttpUrl[urls.size()])); // process multiget results for (DavResource remote : davCollection.members) { String eTag; GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME); if (getETag != null) eTag = getETag.eTag; else throw new DavException("Received multi-get response without ETag"); Charset charset = Charsets.UTF_8; GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME); if (getContentType != null && getContentType.type != null) { MediaType type = MediaType.parse(getContentType.type); if (type != null) charset = type.charset(Charsets.UTF_8); } CalendarData calendarData = (CalendarData) remote.properties.get(CalendarData.NAME); if (calendarData == null || calendarData.iCalendar == null) throw new DavException("Received multi-get response without address data"); @Cleanup InputStream stream = new ByteArrayInputStream(calendarData.iCalendar.getBytes()); processVEvent(remote.fileName(), eTag, stream, charset); } } } }
From source file:org.apache.flink.test.cancelling.CancellingTestBase.java
public void runAndCancelJob(Plan plan, int msecsTillCanceling, int maxTimeTillCanceled) throws Exception { try {/*www.j a v a 2 s . co m*/ // submit job final JobGraph jobGraph = getJobGraph(plan); final long startingTime = System.currentTimeMillis(); long cancelTime = -1L; final JobClient client = this.executor.getJobClient(jobGraph); final JobSubmissionResult submissionResult = client.submitJob(); if (submissionResult.getReturnCode() != AbstractJobResult.ReturnCode.SUCCESS) { throw new IllegalStateException(submissionResult.getDescription()); } final int interval = client.getRecommendedPollingInterval(); final long sleep = interval * 1000L; Thread.sleep(sleep / 2); long lastProcessedEventSequenceNumber = -1L; while (true) { if (Thread.interrupted()) { throw new IllegalStateException("Job client has been interrupted"); } final long now = System.currentTimeMillis(); if (cancelTime < 0L) { // Cancel job if (startingTime + msecsTillCanceling < now) { LOG.info("Issuing cancel request"); final JobCancelResult jcr = client.cancelJob(); if (jcr == null) { throw new IllegalStateException("Return value of cancelJob is null!"); } if (jcr.getReturnCode() != AbstractJobResult.ReturnCode.SUCCESS) { throw new IllegalStateException(jcr.getDescription()); } // Save when the cancel request has been issued cancelTime = now; } } else { // Job has already been canceled if (cancelTime + maxTimeTillCanceled < now) { throw new IllegalStateException("Cancelling of job took " + (now - cancelTime) + " milliseconds, only " + maxTimeTillCanceled + " milliseconds are allowed"); } } final JobProgressResult jobProgressResult = client.getJobProgress(); if (jobProgressResult == null) { throw new IllegalStateException("Returned job progress is unexpectedly null!"); } if (jobProgressResult.getReturnCode() == AbstractJobResult.ReturnCode.ERROR) { throw new IllegalStateException( "Could not retrieve job progress: " + jobProgressResult.getDescription()); } boolean exitLoop = false; final Iterator<AbstractEvent> it = jobProgressResult.getEvents(); while (it.hasNext()) { final AbstractEvent event = it.next(); // Did we already process that event? if (lastProcessedEventSequenceNumber >= event.getSequenceNumber()) { continue; } lastProcessedEventSequenceNumber = event.getSequenceNumber(); // Check if we can exit the loop if (event instanceof JobEvent) { final JobEvent jobEvent = (JobEvent) event; final JobStatus jobStatus = jobEvent.getCurrentJobStatus(); switch (jobStatus) { case FINISHED: throw new IllegalStateException("Job finished successfully"); case FAILED: throw new IllegalStateException("Job failed"); case CANCELED: exitLoop = true; break; case SCHEDULED: // okay case RUNNING: break; default: throw new Exception("Bug: Unrecognized Job Status."); } } if (exitLoop) { break; } } if (exitLoop) { break; } Thread.sleep(sleep); } } catch (Exception e) { LOG.error(e); Assert.fail(StringUtils.stringifyException(e)); return; } }
From source file:com.android.unit_tests.TestHttpServer.java
public void start() { if (this.listener != null) { throw new IllegalStateException("Listener already running"); }//from w w w .j ava 2 s .c o m this.listener = new Thread(new Runnable() { public void run() { while (!shutdown && !Thread.interrupted()) { try { // Set up HTTP connection HttpServerConnection conn = acceptConnection(); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, connStrategy, responseFactory); httpService.setParams(params); httpService.setExpectationVerifier(expectationVerifier); httpService.setHandlerResolver(reqistry); // Start worker thread Thread t = new WorkerThread(httpService, conn); t.setDaemon(true); t.start(); } catch (InterruptedIOException ex) { break; } catch (IOException e) { break; } } } }); this.listener.start(); }
From source file:com.floreantpos.jasperreport.engine.print.JRPrinterAWT.java
/** * *///from ww w .j a va 2 s . co m public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { if (Thread.interrupted()) { throw new PrinterException("Current thread interrupted."); } pageIndex += pageOffset; if (pageIndex < 0 || pageIndex >= jasperPrint.getPages().size()) { return Printable.NO_SUCH_PAGE; } try { JRGraphics2DExporter exporter = new JRGraphics2DExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, this.jasperPrint); exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, graphics); exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(pageIndex)); exporter.exportReport(); } catch (JRException e) { if (log.isDebugEnabled()) log.debug("Print failed.", e); throw new PrinterException(e.getMessage()); } return Printable.PAGE_EXISTS; }