List of usage examples for java.lang Thread interrupted
public static boolean interrupted()
From source file:dk.netarkivet.common.utils.ProcessUtils.java
/** Wait for the end of a process, but only for a limited time. This * method takes care of the ways waitFor can get interrupted. * * @param p Process to wait for//from w w w .j a v a 2 s . c o m * @param maxWait The maximum number of milliseconds to wait for the * process to exit. * @return Exit value for process, or null if the process didn't exit * within the expected time. */ public static Integer waitFor(final Process p, long maxWait) { ArgumentNotValid.checkNotNull(p, "Process p"); ArgumentNotValid.checkPositive(maxWait, "long maxWait"); long startTime = System.currentTimeMillis(); Timer timer = new Timer(true); final Thread waitThread = Thread.currentThread(); boolean wakeupScheduled = false; final AtomicBoolean doneWaiting = new AtomicBoolean(false); while (System.currentTimeMillis() < startTime + maxWait) { try { if (!wakeupScheduled) { // First time in here, we need to start the wakup thread, // but be sure it doesn't notify us too early or too late. synchronized (waitThread) { timer.schedule(new TimerTask() { public void run() { synchronized (waitThread) { if (!doneWaiting.get()) { waitThread.interrupt(); } } } }, maxWait); wakeupScheduled = true; } } p.waitFor(); break; } catch (InterruptedException e) { // May happen for a number of reasons. We just check if we've // timed out yet when we go through the loop again. } } synchronized (waitThread) { timer.cancel(); doneWaiting.set(true); Thread.interrupted(); // In case the timer task interrupted. } try { return p.exitValue(); } catch (IllegalThreadStateException e) { log.warn("Process '" + p + "' did not exit within " + (System.currentTimeMillis() - startTime) + " milliseconds"); return null; } }
From source file:eu.stratosphere.nephele.client.JobClient.java
/** * Submits the job assigned to this job client to the job manager and queries the job manager * about the progress of the job until it is either finished or aborted. * // w ww . j a v a2 s.c om * @return the duration of the job execution in milliseconds * @throws IOException * thrown if an error occurred while transmitting the request * @throws JobExecutionException * thrown if the job has been aborted either by the user or as a result of an error */ public JobExecutionResult submitJobAndWait() throws IOException, JobExecutionException { synchronized (this.jobSubmitClient) { final JobSubmissionResult submissionResult = this.jobSubmitClient.submitJob(this.jobGraph); if (submissionResult.getReturnCode() == AbstractJobResult.ReturnCode.ERROR) { LOG.error("ERROR: " + submissionResult.getDescription()); throw new JobExecutionException(submissionResult.getDescription(), false); } // Make sure the job is properly terminated when the user shut's down the client Runtime.getRuntime().addShutdownHook(this.jobCleanUp); } long sleep = 0; try { final IntegerRecord interval = this.jobSubmitClient.getRecommendedPollingInterval(); sleep = interval.getValue() * 1000; } catch (IOException ioe) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); // Rethrow error throw ioe; } try { Thread.sleep(sleep / 2); } catch (InterruptedException e) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); logErrorAndRethrow(StringUtils.stringifyException(e)); } long startTimestamp = -1; while (true) { if (Thread.interrupted()) { logErrorAndRethrow("Job client has been interrupted"); } JobProgressResult jobProgressResult = null; try { jobProgressResult = getJobProgress(); } catch (IOException ioe) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); // Rethrow error throw ioe; } if (jobProgressResult == null) { logErrorAndRethrow("Returned job progress is unexpectedly null!"); } if (jobProgressResult.getReturnCode() == AbstractJobResult.ReturnCode.ERROR) { logErrorAndRethrow("Could not retrieve job progress: " + jobProgressResult.getDescription()); } final Iterator<AbstractEvent> it = jobProgressResult.getEvents(); while (it.hasNext()) { final AbstractEvent event = it.next(); // Did we already process that event? if (this.lastProcessedEventSequenceNumber >= event.getSequenceNumber()) { continue; } LOG.info(event.toString()); if (this.console != null) { this.console.println(event.toString()); } this.lastProcessedEventSequenceNumber = event.getSequenceNumber(); // Check if we can exit the loop if (event instanceof JobEvent) { final JobEvent jobEvent = (JobEvent) event; final JobStatus jobStatus = jobEvent.getCurrentJobStatus(); if (jobStatus == JobStatus.SCHEDULED) { startTimestamp = jobEvent.getTimestamp(); } if (jobStatus == JobStatus.FINISHED) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); final long jobDuration = jobEvent.getTimestamp() - startTimestamp; // Request accumulators Map<String, Object> accumulators = null; try { accumulators = AccumulatorHelper.toResultMap(getAccumulators().getAccumulators()); } catch (IOException ioe) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); throw ioe; // Rethrow error } return new JobExecutionResult(jobDuration, accumulators); } else if (jobStatus == JobStatus.CANCELED || jobStatus == JobStatus.FAILED) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); LOG.info(jobEvent.getOptionalMessage()); if (jobStatus == JobStatus.CANCELED) { throw new JobExecutionException(jobEvent.getOptionalMessage(), true); } else { throw new JobExecutionException(jobEvent.getOptionalMessage(), false); } } } } try { Thread.sleep(sleep); } catch (InterruptedException e) { logErrorAndRethrow(StringUtils.stringifyException(e)); } } }
From source file:org.kchine.rpf.db.DBLayer.java
public Remote lookup(String name) throws RemoteException, NotBoundException, AccessException { Statement stmt = null;//from ww w . j ava 2 s . c o m ResultSet rset = null; try { checkConnection(); stmt = _connection.createStatement(); rset = stmt.executeQuery("select STUB_HEX,CODEBASE from SERVANTS where NAME='" + name + "'"); if (rset.next()) { final String stubHex = rset.getString(1); final String codeBaseStr = rset.getString(2); final ClassLoader cl = (codeBaseStr != null ? new URLClassLoader(PoolUtils.getURLS(codeBaseStr), DBLayer.class.getClassLoader()) : DBLayer.class.getClassLoader()); System.out.println("codeBaseStr ::" + codeBaseStr); final Object[] resultHolder = new Object[1]; Runnable lookupRunnable = new Runnable() { public void run() { try { resultHolder[0] = hexToStub(stubHex, cl); } catch (Exception e) { final boolean wasInterrupted = Thread.interrupted(); if (wasInterrupted) { resultHolder[0] = new LookUpInterrupted(); } else { resultHolder[0] = e; } } } }; Thread lookupThread = InterruptibleRMIThreadFactory.getInstance().newThread(lookupRunnable); lookupThread.start(); long t1 = System.currentTimeMillis(); while (resultHolder[0] == null) { if ((System.currentTimeMillis() - t1) > PoolUtils.LOOKUP_TIMEOUT_MILLISEC) { lookupThread.interrupt(); resultHolder[0] = new LookUpTimeout(); registerPingFailure(name); break; } Thread.sleep(10); } if (resultHolder[0] instanceof Throwable) { if (resultHolder[0] instanceof NotBoundException) throw (NotBoundException) resultHolder[0]; else throw (RemoteException) resultHolder[0]; } return (Remote) resultHolder[0]; } else { throw new NotBoundException(); } } catch (NotBoundException nbe) { throw nbe; } catch (AccessException ae) { throw ae; } catch (LookUpTimeout lue) { throw lue; } catch (LookUpInterrupted lui) { throw lui; } catch (SQLException sqle) { if (isNoConnectionError(sqle) && canReconnect()) { return lookup(name); } else { throw new RemoteException("", (sqle)); } } catch (Exception e) { throw new RemoteException("", (e)); } finally { if (rset != null) try { stmt.close(); } catch (Exception e) { throw new RemoteException("", (e)); } if (stmt != null) try { stmt.close(); } catch (Exception e) { throw new RemoteException("", (e)); } } }
From source file:de.kiwiwings.jasperreports.exporter.PptxShapeExporter.java
/** * *//* w w w . ja v a 2 s . c o m*/ protected void exportReportToStream(OutputStream os) throws JRException, IOException { ppt = new XMLSlideShow(); ppt.setPageSize(new Dimension(jasperPrint.getPageWidth(), jasperPrint.getPageHeight())); int nbrBackElem = 0; if (itemConfiguration.hasBackground()) { nbrBackElem = exportBackground(); } List<ExporterInputItem> items = exporterInput.getItems(); for (reportIndex = 0; reportIndex < items.size(); reportIndex++) { ExporterInputItem item = items.get(reportIndex); setCurrentExporterInputItem(item); setExporterHints(); slideList.clear(); List<JRPrintPage> pages = jasperPrint.getPages(); if (pages == null || pages.size() == 0) continue; PageRange pageRange = getPageRange(); int startPageIndex = (pageRange == null || pageRange.getStartPageIndex() == null) ? 0 : pageRange.getStartPageIndex(); int endPageIndex = (pageRange == null || pageRange.getEndPageIndex() == null) ? (pages.size() - 1) : pageRange.getEndPageIndex(); // pre-create pages for hyperlinks between them for (int i = startPageIndex; i <= endPageIndex; i++) { createSlide(null);//FIXMEPPTX slideList.put(i, slide); } JRPrintPage page = null; for (pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) { if (Thread.interrupted()) { throw new JRException("Current thread interrupted."); } page = pages.get(pageIndex); slide = slideList.get(pageIndex); List<JRPrintElement> list = page.getElements(); list = list.subList(nbrBackElem, list.size()); page.setElements(list); exportPage(page); SheetCustomizer sheetCustomizer[] = itemConfiguration.getSheetCustomizer(); if (sheetCustomizer != null) { for (SheetCustomizer sc : sheetCustomizer) { sc.customize(slide); } } } } embedFonts(); ppt.write(os); }
From source file:de.micromata.genome.chronos.spi.DispatcherImpl2.java
protected void runLoop() { String runContext = HostUtils.getRunContext(); ScopedLogContextAttribute threadContextScope = new ScopedLogContextAttribute( GenomeAttributeType.ThreadContext, runContext); ScopedLogContextAttribute threadContextScope2 = new ScopedLogContextAttribute( GenomeAttributeType.HttpSessionId, runContext); try {// ww w .j a va 2s . co m /** * @logging * @reason Chronos Dispatcher ist gestartet * @action Keine */ GLog.note(GenomeLogCategory.Scheduler, "Dispatcher run started"); int loopCount = 0; long nextJobTime = -1; while (Thread.interrupted() == false) { try { ++loopCount; initOneLoop(); if (loopCount < 0) { loopCount = 0; } long now = System.currentTimeMillis(); try { if (GLog.isTraceEnabled() == true) { GLog.trace(GenomeLogCategory.Scheduler, "Checking schedulers"); } checkJobsInDB(); resumeImmediatelly = false; nextJobTime = checkJobsToRun(); if (GLog.isTraceEnabled() == true) { GLog.trace(GenomeLogCategory.Scheduler, "Checked schedulers. NextJobTime: " + JobDebugUtils.dateToString(nextJobTime)); } } catch (final Throwable ex) { nextJobTime = -1;// Ohne dies, wird timeout == 0 unten und der Thread schlft immer // da nextJobTime alt ist und n current isr ergebit sich eine negative Zahl, so dass es kleiner ist als minNodeBindTime // Somit wird timout durch timeout = nextJobTime - n; negativ und thread schlft mit timout(0) fr immer, bis notify kommt. /** * @logging * @reason Chronos Dispatcher hat einen Fehler entdeckt * @action Abhaengig von der Exception Entwickler kontaktieren */ GLog.error(GenomeLogCategory.Scheduler, "Error while dispatching: " + ex, new LogExceptionAttribute(ex)); } if (resumeImmediatelly == true) { continue; } long timeout = minNodeBindTime; if (nextJobTime != -1 && nextJobTime - now < minNodeBindTime) { timeout = nextJobTime - now; } if (timeout < 0) { timeout = 0; } if (GLog.isInfoEnabled() == true) { GLog.info(GenomeLogCategory.Scheduler, "dispatcher go sleeping: " + timeout + " ms; nextJobTimeout: " + (nextJobTime == -1 ? "none" : Long.toString(nextJobTime - now))); } if (waitInternal(timeout) == true) { break; } } catch (Throwable ex) { // NOSONAR "Illegal Catch" framework try { /** * @logging * @reason Error in Dispatcher thread while looping * @action Entwickler kontaktieren */ GLog.error(GenomeLogCategory.Scheduler, "Error in Dispatcher thread: " + ex.getMessage(), new LogExceptionAttribute(ex)); } catch (Throwable ex2) { // NOSONAR "Illegal Catch" framework log.error("Dispatcher; Failed to log: " + ex2.getMessage(), ex); } try { Thread.sleep(threadSleepAfterExceptionMs); } catch (InterruptedException ei) { break; } } } GLog.note(GenomeLogCategory.Scheduler, "Dispatcher run finished"); } finally { if (threadContextScope != null) { threadContextScope.restore(); } if (threadContextScope2 != null) { threadContextScope2.restore(); } } }
From source file:com.btoddb.fastpersitentqueue.Fpq.java
public void shutdown() { // stop new transactions, and opertions on FPQ shuttingDown = true;/*w w w. jav a 2 s. co m*/ // give customer clients to to react by committing or rolling back long endTime = System.currentTimeMillis() + waitBeforeKillOnShutdown; while (!activeContexts.isEmpty() && System.currentTimeMillis() < endTime) { try { Thread.sleep(500); } catch (InterruptedException e) { // ignore Thread.interrupted(); } } shutdownLock.writeLock().lock(); try { // any pop'ed entries in progress will be preserved by journals for (FpqContext context : activeContexts.keySet()) { cleanupTransaction(context); } if (null != memoryMgr) { memoryMgr.shutdown(); } if (null != journalMgr) { journalMgr.shutdown(); } } finally { shutdownLock.writeLock().unlock(); } }
From source file:com.opengamma.engine.cache.BerkeleyDBValueIdentifierMapTest.java
@Test(timeOut = 30000) public void interruptThread() throws Throwable { final ExecutorService threads = Executors.newSingleThreadExecutor(); try {/*from w ww. j a v a 2s .com*/ final Thread main = Thread.currentThread(); final Runnable interrupter = new Runnable() { @Override public void run() { try { Thread.sleep(1000); main.interrupt(); } catch (InterruptedException e) { throw new OpenGammaRuntimeException("Interrupted", e); } } }; threads.submit(interrupter); int count = 0; do { try { getPerformanceTest(); } catch (OpenGammaRuntimeException e) { assertEquals("Interrupted", e.getMessage()); count++; if (count <= 5) { threads.submit(interrupter); } else { break; } } } while (true); } finally { threads.shutdown(); Thread.interrupted(); threads.awaitTermination(5, TimeUnit.SECONDS); } }
From source file:com.github.pascalgn.jiracli.web.HttpClient.java
private <T> T doExecute(HttpUriRequest request, boolean retry, Function<HttpEntity, T> function) { LOGGER.debug("Calling URL: {} [{}]", request.getURI(), request.getMethod()); // disable XSRF check: if (!request.containsHeader("X-Atlassian-Token")) { request.addHeader("X-Atlassian-Token", "nocheck"); }/*www .j av a 2 s. c o m*/ HttpResponse response; try { response = httpClient.execute(request, httpClientContext); } catch (IOException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw new IllegalStateException("Could not call URL: " + request.getURI(), e); } } LOGGER.debug("Response received ({})", response.getStatusLine().toString().trim()); HttpEntity entity = response.getEntity(); try { if (Thread.interrupted()) { throw new InterruptedError(); } int statusCode = response.getStatusLine().getStatusCode(); if (isSuccess(statusCode)) { T result; try { result = function.apply(entity, Hint.none()); } catch (NotAuthenticatedException e) { if (retry) { resetAuthentication(); setCredentials(); return doExecute(request, false, function); } else { throw e.getCause(); } } catch (RuntimeException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw e; } } if (Thread.interrupted()) { throw new InterruptedError(); } return result; } else { if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { resetAuthentication(); if (retry) { setCredentials(); return doExecute(request, false, function); } else { String error = readErrorResponse(request.getURI(), entity); LOGGER.debug("Unauthorized [401]: {}", error); throw new AccessControlException("Unauthorized [401]: " + request.getURI()); } } else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) { resetAuthentication(); checkAccountLocked(response); if (retry) { setCredentials(); return doExecute(request, false, function); } else { throw new AccessControlException("Forbidden [403]: " + request.getURI()); } } else { String status = response.getStatusLine().toString().trim(); String message; if (entity == null) { message = status; } else { String error = readErrorResponse(request.getURI(), entity); message = status + (error.isEmpty() ? "" : ": " + error); } if (Thread.interrupted()) { throw new InterruptedError(); } if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) { throw new NoSuchElementException(message); } else { throw new IllegalStateException(message); } } } } finally { EntityUtils.consumeQuietly(entity); } }
From source file:org.apache.flink.runtime.client.JobClient.java
/** * Submits the job assigned to this job client to the job manager and queries the job manager * about the progress of the job until it is either finished or aborted. * // w w w . j a v a2s. c o m * @return the duration of the job execution in milliseconds * @throws IOException * thrown if an error occurred while transmitting the request * @throws JobExecutionException * thrown if the job has been aborted either by the user or as a result of an error */ public JobExecutionResult submitJobAndWait() throws IOException, JobExecutionException { synchronized (this.jobSubmitClient) { final JobSubmissionResult submissionResult = this.jobSubmitClient.submitJob(this.jobGraph); if (submissionResult.getReturnCode() == AbstractJobResult.ReturnCode.ERROR) { LOG.error("ERROR: " + submissionResult.getDescription()); throw new JobExecutionException(submissionResult.getDescription(), false); } // Make sure the job is properly terminated when the user shut's down the client Runtime.getRuntime().addShutdownHook(this.jobCleanUp); } long sleep = 0; try { final IntegerRecord interval = this.jobSubmitClient.getRecommendedPollingInterval(); sleep = interval.getValue() * 1000; } catch (IOException ioe) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); // Rethrow error throw ioe; } try { Thread.sleep(sleep / 2); } catch (InterruptedException e) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); logErrorAndRethrow(StringUtils.stringifyException(e)); } long startTimestamp = -1; while (true) { if (Thread.interrupted()) { logErrorAndRethrow("Job client has been interrupted"); } JobProgressResult jobProgressResult = null; try { jobProgressResult = getJobProgress(); } catch (IOException ioe) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); // Rethrow error throw ioe; } if (jobProgressResult == null) { logErrorAndRethrow("Returned job progress is unexpectedly null!"); } if (jobProgressResult.getReturnCode() == AbstractJobResult.ReturnCode.ERROR) { logErrorAndRethrow("Could not retrieve job progress: " + jobProgressResult.getDescription()); } final Iterator<AbstractEvent> it = jobProgressResult.getEvents(); while (it.hasNext()) { final AbstractEvent event = it.next(); // Did we already process that event? if (this.lastProcessedEventSequenceNumber >= event.getSequenceNumber()) { continue; } LOG.info(event.toString()); if (this.console != null) { this.console.println(event.toString()); } this.lastProcessedEventSequenceNumber = event.getSequenceNumber(); // Check if we can exit the loop if (event instanceof JobEvent) { final JobEvent jobEvent = (JobEvent) event; final JobStatus jobStatus = jobEvent.getCurrentJobStatus(); if (jobStatus == JobStatus.SCHEDULED) { startTimestamp = jobEvent.getTimestamp(); } if (jobStatus == JobStatus.FINISHED) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); final long jobDuration = jobEvent.getTimestamp() - startTimestamp; // Request accumulators Map<String, Object> accumulators = null; try { accumulators = AccumulatorHelper .toResultMap(getAccumulators().getAccumulators(this.userCodeClassLoader)); } catch (IOException ioe) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); throw ioe; // Rethrow error } return new JobExecutionResult(jobDuration, accumulators); } else if (jobStatus == JobStatus.CANCELED || jobStatus == JobStatus.FAILED) { Runtime.getRuntime().removeShutdownHook(this.jobCleanUp); LOG.info(jobEvent.getOptionalMessage()); if (jobStatus == JobStatus.CANCELED) { throw new JobExecutionException(jobEvent.getOptionalMessage(), true); } else { throw new JobExecutionException(jobEvent.getOptionalMessage(), false); } } } } try { Thread.sleep(sleep); } catch (InterruptedException e) { logErrorAndRethrow(StringUtils.stringifyException(e)); } } }
From source file:at.bitfire.davdroid.syncadapter.SyncManager.java
/** * Process locally deleted entries (DELETE them on the server as well). * Checks Thread.interrupted() before each request to allow quick sync cancellation. *//*from w w w .j a va 2 s . c o m*/ protected void processLocallyDeleted() throws CalendarStorageException, ContactsStorageException { // Remove locally deleted entries from server (if they have a name, i.e. if they were uploaded before), // but only if they don't have changed on the server. Then finally remove them from the local address book. LocalResource[] localList = localCollection.getDeleted(); for (LocalResource local : localList) { if (Thread.interrupted()) return; final String fileName = local.getFileName(); if (!TextUtils.isEmpty(fileName)) { App.log.info(fileName + " has been deleted locally -> deleting from server"); try { new DavResource(httpClient, collectionURL.newBuilder().addPathSegment(fileName).build()) .delete(local.getETag()); } catch (IOException | HttpException e) { App.log.warning( "Couldn't delete " + fileName + " from server; ignoring (may be downloaded again)"); } } else App.log.info("Removing local record #" + local.getId() + " which has been deleted locally and was never uploaded"); local.delete(); syncResult.stats.numDeletes++; } }