List of usage examples for java.lang Thread interrupted
public static boolean interrupted()
From source file:jenkins.branch.OrganizationFolder.java
/** * {@inheritDoc}/*from www.j a va 2 s . co m*/ */ @Override protected void computeChildren(final ChildObserver<MultiBranchProject<?, ?>> observer, final TaskListener listener) throws IOException, InterruptedException { // capture the current digests to prevent unnecessary rescan if re-saving after scan try { navDigest = Util.getDigestOf(Items.XSTREAM2.toXML(navigators)); } catch (XStreamException e) { navDigest = null; } try { facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(projectFactories)); } catch (XStreamException e) { facDigest = null; } long start = System.currentTimeMillis(); listener.getLogger().format("[%tc] Starting organization scan...%n", start); try { listener.getLogger().format("[%tc] Updating actions...%n", System.currentTimeMillis()); Map<SCMNavigator, List<Action>> navigatorActions = new HashMap<>(); for (SCMNavigator navigator : navigators) { List<Action> actions; try { actions = navigator.fetchActions(this, null, listener); } catch (IOException e) { MultiBranchProject.printStackTrace(e, listener.error("[%tc] Could not refresh actions for navigator %s", System.currentTimeMillis(), navigator)); // preserve previous actions if we have some transient error fetching now (e.g. API rate limit) actions = Util.fixNull(state.getActions().get(navigator)); } navigatorActions.put(navigator, actions); } // update any persistent actions for the SCMNavigator if (!navigatorActions.equals(state.getActions())) { boolean saveProject = false; for (List<Action> actions : navigatorActions.values()) { for (Action a : actions) { // undo any hacks that attached the contributed actions without attribution saveProject = removeActions(a.getClass()) || saveProject; } } BulkChange bc = new BulkChange(state); try { state.setActions(navigatorActions); try { bc.commit(); } catch (IOException | RuntimeException e) { MultiBranchProject.printStackTrace(e, listener .error("[%tc] Could not persist folder level actions", System.currentTimeMillis())); throw e; } if (saveProject) { try { save(); } catch (IOException | RuntimeException e) { MultiBranchProject.printStackTrace(e, listener.error("[%tc] Could not persist folder level configuration changes", System.currentTimeMillis())); throw e; } } } finally { bc.abort(); } } for (SCMNavigator navigator : navigators) { if (Thread.interrupted()) { throw new InterruptedException(); } listener.getLogger().format("[%tc] Consulting %s%n", System.currentTimeMillis(), navigator.getDescriptor().getDisplayName()); try { navigator.visitSources( new SCMSourceObserverImpl(listener, observer, navigator, (SCMSourceEvent<?>) null)); } catch (IOException | InterruptedException | RuntimeException e) { MultiBranchProject.printStackTrace(e, listener.error("[%tc] Could not fetch sources from navigator %s", System.currentTimeMillis(), navigator)); throw e; } } } finally { long end = System.currentTimeMillis(); listener.getLogger().format("[%tc] Finished organization scan. Scan took %s%n", end, Util.getTimeSpanString(end - start)); } }
From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java
/** * Returns cached data for the given hash locally. This method can be used when storage if fully * downloaded.//from ww w .ja v a 2 s .c o m * * @param <E> * Type of the objects are wanted. * * @param localStorageData * {@link LocalStorageData} that points to the wanted storage. * @param hash * Hash under which the cached data is stored. * @return Returns cached data for the storage if the cached data exists for given hash. If data * does not exist <code>null</code> is returned. * @throws SerializationException * If {@link SerializationException} occurs. * @throws IOException * If {@link IOException} occurs. */ @SuppressWarnings("unchecked") public <E extends DefaultData> List<E> getCachedDataLocally(LocalStorageData localStorageData, int hash) throws IOException, SerializationException { Path path = storageManager.getCachedDataPath(localStorageData, hash); if (Files.notExists(path)) { return null; } else { ISerializer serializer = null; try { serializer = serializerQueue.take(); } catch (InterruptedException e) { Thread.interrupted(); } Input input = null; try (InputStream inputStream = Files.newInputStream(path, StandardOpenOption.READ)) { input = new Input(inputStream); Object object = serializer.deserialize(input); List<E> receivedData = (List<E>) object; return receivedData; } finally { if (null != input) { input.close(); } serializerQueue.add(serializer); } } }
From source file:com.yahoo.ads.pb.kafka.KafkaSimpleConsumer.java
private PartitionMetadata findLeader() throws InterruptedException { List<String> topics = new ArrayList<String>(); topics.add(topic);//www . j a v a2s . c o m for (KafkaBroker broker : replicaBrokers) { SimpleConsumer consumer = null; try { logger.debug("findLeader, try broker {}:{}", broker.host, broker.port); consumer = new SimpleConsumer(broker.host, broker.port, conf.getInt("Pistachio.Kafka.soTimeout"), conf.getInt("Pistachio.Kafka.bufferSize"), clientId + "leaderLookup"); TopicMetadataResponse resp = consumer.send(new TopicMetadataRequest(topics)); // just one topic inside the topics List<TopicMetadata> metaData = resp.topicsMetadata(); for (TopicMetadata item : metaData) { for (PartitionMetadata part : item.partitionsMetadata()) { if (part.partitionId() == partitionId) { replicaBrokers.clear(); for (Broker replica : part.replicas()) { replicaBrokers.add(new KafkaBroker(replica.host(), replica.port())); } return part; } } } } catch (Exception e) { // e could be an instance of ClosedByInterruptException as SimpleConsumer.send uses nio if (Thread.interrupted()) { logger.info("catch exception of {} with interrupted in find leader for {} - {}", e.getClass().getName(), topic, partitionId); throw new InterruptedException(); } logger.warn("error communicating with Broker {} to find leader for {} - {}", broker, topic, partitionId, e); } finally { if (consumer != null) { try { consumer.close(); } catch (Exception e) { } } } } return null; }
From source file:org.apache.hadoop.dfs.DataBlockScanner.java
/** returns false if the process was interrupted * because the thread is marked to exit. *///from w w w. jav a 2 s. c o m private boolean assignInitialVerificationTimes() { int numBlocks = 1; synchronized (this) { numBlocks = Math.max(blockMap.size(), 1); } //First udpates the last verification times from the log file. LogFileHandler.Reader logReader = null; try { if (verificationLog != null) { logReader = verificationLog.new Reader(false); } } catch (IOException e) { LOG.warn("Could not read previous verification times : " + StringUtils.stringifyException(e)); } if (verificationLog != null) { verificationLog.updateCurNumLines(); } // update verification times from the verificationLog. while (logReader != null && logReader.hasNext()) { if (!datanode.shouldRun || Thread.interrupted()) { return false; } LogEntry entry = LogEntry.parseEntry(logReader.next()); if (entry != null) { updateBlockInfo(entry); } } /* Initially spread the block reads over half of * MIN_SCAN_PERIOD so that we don't keep scanning the * blocks too quickly when restarted. */ long verifyInterval = (long) (Math.min(scanPeriod / 2.0 / numBlocks, 10 * 60 * 1000)); long lastScanTime = System.currentTimeMillis() - scanPeriod; /* Before this loop, entries in blockInfoSet that are not * updated above have lastScanTime of <= 0 . Loop until first entry has * lastModificationTime > 0. */ synchronized (this) { if (blockInfoSet.size() > 0) { BlockScanInfo info; while ((info = blockInfoSet.first()).lastScanTime < 0) { delBlockInfo(info); info.lastScanTime = lastScanTime; lastScanTime += verifyInterval; addBlockInfo(info); } } } return true; }
From source file:com.datatorrent.stram.StramLocalCluster.java
@Override @SuppressWarnings({ "SleepWhileInLoop", "ResultOfObjectAllocationIgnored" }) public void run(long runMillis) { long endMillis = System.currentTimeMillis() + runMillis; while (!appDone) { for (String containerIdStr : dnmgr.containerStopRequests.values()) { // teardown child thread StreamingContainer c = childContainers.get(containerIdStr); if (c != null) { ContainerHeartbeatResponse r = new ContainerHeartbeatResponse(); r.shutdown = true;/*from www. j av a 2s . c o m*/ c.processHeartbeatResponse(r); } dnmgr.containerStopRequests.remove(containerIdStr); LOG.info("Container {} restart.", containerIdStr); dnmgr.scheduleContainerRestart(containerIdStr); //dnmgr.removeContainerAgent(containerIdStr); } // start containers while (!dnmgr.containerStartRequests.isEmpty()) { ContainerStartRequest cdr = dnmgr.containerStartRequests.poll(); if (cdr != null) { new LocalStramChildLauncher(cdr); } } if (heartbeatMonitoringEnabled) { // monitor child containers dnmgr.monitorHeartbeat(); } if (childContainers.isEmpty() && dnmgr.containerStartRequests.isEmpty()) { appDone = true; } if (runMillis > 0 && System.currentTimeMillis() > endMillis) { appDone = true; } try { if (exitCondition != null && exitCondition.call()) { appDone = true; } } catch (Exception ex) { break; } if (Thread.interrupted()) { break; } if (!appDone) { try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.info("Sleep interrupted " + e.getMessage()); break; } } } for (LocalStreamingContainer lsc : childContainers.values()) { injectShutdown.put(lsc.getContainerId(), lsc); lsc.triggerHeartbeat(); } dnmgr.teardown(); LOG.info("Application finished."); if (!perContainerBufferServer) { StreamingContainer.eventloop.stop(bufferServer); StreamingContainer.eventloop.stop(); } }
From source file:net.sf.jasperreports.engine.export.JsonMetadataExporter.java
protected void exportReportToWriter() throws JRException, IOException { List<ExporterInputItem> items = exporterInput.getItems(); for (reportIndex = 0; reportIndex < items.size(); reportIndex++)//FIXMEJSONMETA deal with batch export {/*from w w w .j ava 2 s . c o m*/ ExporterInputItem item = items.get(reportIndex); setCurrentExporterInputItem(item); JsonMetadataReportConfiguration currentItemConfiguration = getCurrentItemConfiguration(); escapeMembers = currentItemConfiguration.isEscapeMembers(); String jsonSchemaResource = currentItemConfiguration.getJsonSchemaResource(); if (jsonSchemaResource != null) { InputStream is = null; try { is = getRepository().getInputStreamFromLocation(jsonSchemaResource); jsonSchema = new Scanner(is, "UTF-8").useDelimiter("\\A").next(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } validateSchema(jsonSchema); gotSchema = true; } else { if (log.isWarnEnabled()) { log.warn("No JSON Schema provided!"); } } List<JRPrintPage> pages = jasperPrint.getPages(); if (pages != null && pages.size() > 0) { 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(); JRPrintPage page = null; for (pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) { if (Thread.interrupted()) { throw new ExportInterruptedException(); } page = pages.get(pageIndex); exportPage(page); } closeOpenNodes(); } if (log.isDebugEnabled()) { for (Map.Entry<String, SchemaNode> entry : pathToValueNode.entrySet()) { log.debug("pathToValueNode: path: " + entry.getKey() + "; node: " + entry.getValue()); } for (Map.Entry<String, SchemaNode> entry : pathToObjectNode.entrySet()) { log.debug("pathToObjectNode: path: " + entry.getKey() + "; node: " + entry.getValue()); } } } boolean flushOutput = getCurrentConfiguration().isFlushOutput(); if (flushOutput) { writer.flush(); } }
From source file:net.sf.jasperreports.engine.export.ooxml.JRPptxExporter.java
/** * *//*from w w w .j a v a2 s.c om*/ protected void exportReportToStream(OutputStream os) throws JRException, IOException { pptxZip = new PptxZip(); PptxExporterConfiguration configuration = getCurrentConfiguration(); presentationWriter = pptxZip.getPresentationEntry().getWriter(); presentationRelsWriter = pptxZip.getRelsEntry().getWriter(); boolean isEmbedFonts = Boolean.TRUE.equals(configuration.isEmbedFonts()); FileBufferedWriter fontWriter = new FileBufferedWriter(); fontHelper = new PptxFontHelper(jasperReportsContext, fontWriter, presentationRelsWriter, pptxZip, isEmbedFonts); presentationHelper = new PptxPresentationHelper(jasperReportsContext, presentationWriter, fontWriter); presentationHelper.exportHeader(isEmbedFonts); presentationRelsHelper = new PptxPresentationRelsHelper(jasperReportsContext, presentationRelsWriter); presentationRelsHelper.exportHeader(); ctHelper = new PptxContentTypesHelper(jasperReportsContext, pptxZip.getContentTypesEntry().getWriter()); ctHelper.exportHeader(); appHelper = new PropsAppHelper(jasperReportsContext, pptxZip.getAppEntry().getWriter()); coreHelper = new PropsCoreHelper(jasperReportsContext, pptxZip.getCoreEntry().getWriter()); appHelper.exportHeader(); String application = configuration.getMetadataApplication(); if (application == null) { application = "JasperReports Library version " + Package.getPackage("net.sf.jasperreports.engine").getImplementationVersion(); } appHelper.exportProperty(PropsAppHelper.PROPERTY_APPLICATION, application); coreHelper.exportHeader(); String title = configuration.getMetadataTitle(); if (title != null) { coreHelper.exportProperty(PropsCoreHelper.PROPERTY_TITLE, title); } String subject = configuration.getMetadataSubject(); if (subject != null) { coreHelper.exportProperty(PropsCoreHelper.PROPERTY_SUBJECT, subject); } String author = configuration.getMetadataAuthor(); if (author != null) { coreHelper.exportProperty(PropsCoreHelper.PROPERTY_CREATOR, author); } String keywords = configuration.getMetadataKeywords(); if (keywords != null) { coreHelper.exportProperty(PropsCoreHelper.PROPERTY_KEYWORDS, keywords); } Integer slideMasterReport = configuration.getSlideMasterReport(); if (slideMasterReport == null) { slideMasterReport = 1; } int slideMasterReportIndex = slideMasterReport - 1; Integer slideMasterPage = configuration.getSlideMasterPage(); if (slideMasterPage == null) { slideMasterPage = 1; } int slideMasterPageIndex = slideMasterPage - 1; // DocxStyleHelper styleHelper = // new DocxStyleHelper( // null,//pptxZip.getStylesEntry().getWriter(), // fontMap, // getExporterKey() // ); // styleHelper.export(jasperPrintList); // styleHelper.close(); List<ExporterInputItem> items = exporterInput.getItems(); boolean hasSlideMasterElements = false; createSlideMaster(); if (0 <= slideMasterReportIndex && slideMasterReportIndex < items.size()) { if (Thread.interrupted()) { throw new ExportInterruptedException(); } ExporterInputItem item = items.get(slideMasterReportIndex); setCurrentExporterInputItem(item); List<JRPrintPage> pages = jasperPrint.getPages(); if (pages != null && pages.size() > 0) { 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(); if (startPageIndex <= slideMasterPageIndex && slideMasterPageIndex <= endPageIndex) { hasSlideMasterElements = exportPageToSlideMaster(pages.get(slideMasterPageIndex), configuration.isBackgroundAsSlideMaster()); } } } closeSlideMaster(); for (reportIndex = 0; reportIndex < items.size(); reportIndex++) { ExporterInputItem item = items.get(reportIndex); setCurrentExporterInputItem(item); List<JRPrintPage> pages = jasperPrint.getPages(); if (pages != null && pages.size() > 0) { 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(); net.sf.jasperreports.engine.util.PageRange[] hideSmPageRanges = null; String hideSlideMasterPages = getCurrentItemConfiguration().getHideSlideMasterPages(); if (hideSlideMasterPages != null && hideSlideMasterPages.trim().length() > 0) { hideSmPageRanges = net.sf.jasperreports.engine.util.PageRange.parse(hideSlideMasterPages); } for (pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) { if (Thread.interrupted()) { throw new ExportInterruptedException(); } JRPrintPage page = pages.get(pageIndex); createSlide(net.sf.jasperreports.engine.util.PageRange.isPageInRanges(pageIndex + 1, hideSmPageRanges)); slideIndex++; exportPage(page, configuration.isBackgroundAsSlideMaster(), hasSlideMasterElements); closeSlide(); } } } fontHelper.exportFonts(); fontWriter.close(); presentationHelper.exportFooter(jasperPrint); presentationHelper.close(); // if ((hyperlinksMap != null && hyperlinksMap.size() > 0)) // { // for(Iterator it = hyperlinksMap.keySet().iterator(); it.hasNext();) // { // String href = (String)it.next(); // String id = (String)hyperlinksMap.get(href); // // relsHelper.exportHyperlink(id, href); // } // } presentationRelsHelper.exportFooter(); presentationRelsHelper.close(); ctHelper.exportFooter(); ctHelper.close(); appHelper.exportFooter(); appHelper.close(); coreHelper.exportFooter(); coreHelper.close(); pptxZip.zipEntries(os); fontWriter.dispose(); pptxZip.dispose(); }
From source file:com.btoddb.fastpersitentqueue.JournalMgrIT.java
@Test public void testThreading() throws IOException, ExecutionException { final int numEntries = 10000; final int numPushers = 3; int numPoppers = 3; final Random pushRand = new Random(1000L); final Random popRand = new Random(1000000L); final ConcurrentLinkedQueue<FpqEntry> events = new ConcurrentLinkedQueue<FpqEntry>(); final AtomicInteger pusherFinishCount = new AtomicInteger(); final AtomicInteger numPops = new AtomicInteger(); final AtomicLong pushSum = new AtomicLong(); final AtomicLong popSum = new AtomicLong(); mgr.setMaxJournalFileSize(1000);/*w w w. j a va 2 s . com*/ mgr.init(); ExecutorService execSrvc = Executors.newFixedThreadPool(numPushers + numPoppers); Set<Future> futures = new HashSet<Future>(); // start pushing for (int i = 0; i < numPushers; i++) { Future future = execSrvc.submit(new Runnable() { @Override public void run() { for (int i = 0; i < numEntries; i++) { try { long x = idGen.incrementAndGet(); FpqEntry entry = mgr.append(new FpqEntry(x, new byte[100])); events.offer(entry); pushSum.addAndGet(x); if (x % 500 == 0) { System.out.println("pushed ID = " + x); } Thread.sleep(pushRand.nextInt(5)); } catch (Exception e) { e.printStackTrace(); } } pusherFinishCount.incrementAndGet(); } }); futures.add(future); } // start popping for (int i = 0; i < numPoppers; i++) { Future future = execSrvc.submit(new Runnable() { @Override public void run() { while (pusherFinishCount.get() < numPushers || !events.isEmpty()) { try { FpqEntry entry; while (null != (entry = events.poll())) { if (entry.getId() % 500 == 0) { System.out.println("popped ID = " + entry.getId()); } popSum.addAndGet(entry.getId()); numPops.incrementAndGet(); mgr.reportTake(entry); Thread.sleep(popRand.nextInt(5)); } } catch (Exception e) { e.printStackTrace(); } } } }); futures.add(future); } boolean finished = false; while (!finished) { try { for (Future f : futures) { f.get(); } finished = true; } catch (InterruptedException e) { // ignore Thread.interrupted(); } } assertThat(numPops.get(), is(numEntries * numPushers)); assertThat(popSum.get(), is(pushSum.get())); assertThat(mgr.getJournalIdMap().entrySet(), hasSize(1)); assertThat(FileUtils.listFiles(theDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE), hasSize(1)); }
From source file:org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer.java
public synchronized void blockUntilFinished() { lock = new CountDownLatch(1); try {//from w w w . j a v a2 s. c o m synchronized (runners) { while (!runners.isEmpty()) { try { runners.wait(); } catch (InterruptedException e) { Thread.interrupted(); } if (scheduler.isTerminated()) break; // if we reach here, then we probably got the notifyAll, but need to check if // the queue is empty before really considering this is finished (SOLR-4260) int queueSize = queue.size(); if (queueSize > 0) { log.warn("No more runners, but queue still has " + queueSize + " adding more runners to process remaining requests on queue"); Runner r = new Runner(); runners.add(r); scheduler.execute(r); } } } } finally { lock.countDown(); lock = null; } }
From source file:org.janusgraph.diskstorage.BackendTransaction.java
private final <V> V executeRead(Callable<V> exe) throws JanusGraphException { try {/*from w ww. j a va2 s . c o m*/ return BackendOperation.execute(exe, maxReadTime); } catch (JanusGraphException e) { // support traversal interruption // TODO: Refactor to allow direct propagation of underlying interrupt exception if (Thread.interrupted()) throw new TraversalInterruptedException(); throw e; } }