Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:graphene.util.fs.FileUtils.java

private static void waitSome() {
        try {// w w w .ja v  a 2s .com
            Thread.sleep(500);
        } catch (final InterruptedException ee) {
            Thread.interrupted();
        } // ok
        System.gc();
    }

From source file:com.btoddb.fastpersitentqueue.FpqIT.java

private void checkSumByPopping(Fpq fpq, int expectedPops, int expectedSum) throws IOException {
    assertThat(fpq.getNumberOfEntries(), is((long) expectedPops));

    long end = System.currentTimeMillis() + 10000;
    int numPops = 0;
    int sum = 0;/*from   www .ja va 2 s . co m*/
    while (numPops < expectedPops && System.currentTimeMillis() < end) {
        fpq.beginTransaction();
        Collection<FpqEntry> entries = fpq.pop(1);
        if (null != entries && !entries.isEmpty()) {
            numPops += entries.size();
            sum += extractId(entries.iterator().next().getData());
        } else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // ignore
                Thread.interrupted();
            }
        }
        fpq.commit();
    }
    assertThat(numPops, is(expectedPops));
    assertThat(sum, is(expectedSum));
}

From source file:net.sf.jasperreports.engine.export.ooxml.JRDocxExporter.java

/**
 *
 *//* ww  w .j a  va 2 s. c om*/
protected void exportReportToStream(OutputStream os) throws JRException, IOException {
    docxZip = new DocxZip();

    docWriter = docxZip.getDocumentEntry().getWriter();

    docHelper = new DocxDocumentHelper(jasperReportsContext, docWriter);
    docHelper.exportHeader();

    relsHelper = new DocxRelsHelper(jasperReportsContext, docxZip.getRelsEntry().getWriter());
    relsHelper.exportHeader();

    appHelper = new PropsAppHelper(jasperReportsContext, docxZip.getAppEntry().getWriter());
    coreHelper = new PropsCoreHelper(jasperReportsContext, docxZip.getCoreEntry().getWriter());

    appHelper.exportHeader();

    DocxExporterConfiguration configuration = getCurrentConfiguration();

    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);
    }

    List<ExporterInputItem> items = exporterInput.getItems();

    boolean isEmbedFonts = Boolean.TRUE.equals(configuration.isEmbedFonts());

    docxFontHelper = new DocxFontHelper(jasperReportsContext, docxZip, isEmbedFonts);

    DocxStyleHelper styleHelper = new DocxStyleHelper(this, docxZip.getStylesEntry().getWriter(),
            docxFontHelper);
    styleHelper.export(exporterInput);
    styleHelper.close();

    DocxSettingsHelper settingsHelper = new DocxSettingsHelper(jasperReportsContext,
            docxZip.getSettingsEntry().getWriter());
    settingsHelper.export(jasperPrint, isEmbedFonts);
    settingsHelper.close();

    docxFontTableHelper = new DocxFontTableHelper(jasperReportsContext,
            docxZip.getFontTableEntry().getWriter());
    docxFontTableHelper.exportHeader();

    docxFontTableRelsHelper = new DocxFontTableRelsHelper(jasperReportsContext,
            docxZip.getFontTableRelsEntry().getWriter());
    docxFontTableRelsHelper.exportHeader();

    runHelper = new DocxRunHelper(jasperReportsContext, docWriter, docxFontHelper);

    pageFormat = null;
    PrintPageFormat oldPageFormat = null;

    for (reportIndex = 0; reportIndex < items.size(); reportIndex++) {
        ExporterInputItem item = items.get(reportIndex);

        setCurrentExporterInputItem(item);

        bookmarkIndex = 0;
        emptyPageState = false;

        List<JRPrintPage> pages = jasperPrint.getPages();
        if (pages != null && pages.size() > 0) {
            PageRange pageRange = getPageRange();
            startPageIndex = (pageRange == null || pageRange.getStartPageIndex() == null) ? 0
                    : pageRange.getStartPageIndex();
            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);

                pageFormat = jasperPrint.getPageFormat(pageIndex);

                if (oldPageFormat != null && oldPageFormat != pageFormat) {
                    docHelper.exportSection(oldPageFormat, pageGridLayout, false);
                }

                exportPage(page);

                oldPageFormat = pageFormat;
            }
        }
    }

    if (oldPageFormat != null) {
        docHelper.exportSection(oldPageFormat, pageGridLayout, true);
    }

    docHelper.exportFooter();
    docHelper.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);
    //         }
    //      }

    relsHelper.exportFooter();
    relsHelper.close();

    appHelper.exportFooter();
    appHelper.close();

    coreHelper.exportFooter();
    coreHelper.close();

    docxFontHelper.exportFonts();

    docxFontTableHelper.exportFooter();
    docxFontTableHelper.close();

    docxFontTableRelsHelper.exportFooter();
    docxFontTableRelsHelper.close();

    docxZip.zipEntries(os);

    docxZip.dispose();
}

From source file:org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.java

/**
 * Called by {@link #evalOpInternal} when iterating a result set. Implementers should respect the
 * {@link Settings#serializedResponseTimeout} configuration and break the serialization process if
 * it begins to take too long to do so, throwing a {@link java.util.concurrent.TimeoutException} in such
 * cases.//from  www .jav  a2s . c  om
 *
 * @param context The Gremlin Server {@link Context} object containing settings, request message, etc.
 * @param itty The result to iterator
 * @throws TimeoutException if the time taken to serialize the entire result set exceeds the allowable time.
 */
protected void handleIterator(final Context context, final Iterator itty)
        throws TimeoutException, InterruptedException {
    final ChannelHandlerContext ctx = context.getChannelHandlerContext();
    final RequestMessage msg = context.getRequestMessage();
    final Settings settings = context.getSettings();
    final MessageSerializer serializer = ctx.channel().attr(StateKey.SERIALIZER).get();
    final boolean useBinary = ctx.channel().attr(StateKey.USE_BINARY).get();
    boolean warnOnce = false;

    // sessionless requests are always transaction managed, but in-session requests are configurable.
    final boolean managedTransactionsForRequest = manageTransactions ? true
            : (Boolean) msg.getArgs().getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false);

    // we have an empty iterator - happens on stuff like: g.V().iterate()
    if (!itty.hasNext()) {
        // as there is nothing left to iterate if we are transaction managed then we should execute a
        // commit here before we send back a NO_CONTENT which implies success
        if (managedTransactionsForRequest)
            attemptCommit(msg, context.getGraphManager(), settings.strictTransactionManagement);
        ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.NO_CONTENT).create());
        return;
    }

    // timer for the total serialization time
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // the batch size can be overridden by the request
    final int resultIterationBatchSize = (Integer) msg.optionalArgs(Tokens.ARGS_BATCH_SIZE)
            .orElse(settings.resultIterationBatchSize);
    List<Object> aggregate = new ArrayList<>(resultIterationBatchSize);

    // use an external control to manage the loop as opposed to just checking hasNext() in the while.  this
    // prevent situations where auto transactions create a new transaction after calls to commit() withing
    // the loop on calls to hasNext().
    boolean hasMore = itty.hasNext();

    while (hasMore) {
        if (Thread.interrupted())
            throw new InterruptedException();

        // have to check the aggregate size because it is possible that the channel is not writeable (below)
        // so iterating next() if the message is not written and flushed would bump the aggregate size beyond
        // the expected resultIterationBatchSize.  Total serialization time for the response remains in
        // effect so if the client is "slow" it may simply timeout.
        if (aggregate.size() < resultIterationBatchSize)
            aggregate.add(itty.next());

        // send back a page of results if batch size is met or if it's the end of the results being iterated.
        // also check writeability of the channel to prevent OOME for slow clients.
        if (ctx.channel().isWritable()) {
            if (aggregate.size() == resultIterationBatchSize || !itty.hasNext()) {
                final ResponseStatusCode code = itty.hasNext() ? ResponseStatusCode.PARTIAL_CONTENT
                        : ResponseStatusCode.SUCCESS;

                // serialize here because in sessionless requests the serialization must occur in the same
                // thread as the eval.  as eval occurs in the GremlinExecutor there's no way to get back to the
                // thread that processed the eval of the script so, we have to push serialization down into that
                Frame frame;
                try {
                    frame = makeFrame(ctx, msg, serializer, useBinary, aggregate, code);
                } catch (Exception ex) {
                    // exception is handled in makeFrame() - serialization error gets written back to driver
                    // at that point
                    if (manageTransactions)
                        attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
                    break;
                }

                // only need to reset the aggregation list if there's more stuff to write
                if (itty.hasNext())
                    aggregate = new ArrayList<>(resultIterationBatchSize);
                else {
                    // iteration and serialization are both complete which means this finished successfully. note that
                    // errors internal to script eval or timeout will rollback given GremlinServer's global configurations.
                    // local errors will get rolledback below because the exceptions aren't thrown in those cases to be
                    // caught by the GremlinExecutor for global rollback logic. this only needs to be committed if
                    // there are no more items to iterate and serialization is complete
                    if (managedTransactionsForRequest)
                        attemptCommit(msg, context.getGraphManager(), settings.strictTransactionManagement);

                    // exit the result iteration loop as there are no more results left.  using this external control
                    // because of the above commit.  some graphs may open a new transaction on the call to
                    // hasNext()
                    hasMore = false;
                }

                // the flush is called after the commit has potentially occurred.  in this way, if a commit was
                // required then it will be 100% complete before the client receives it. the "frame" at this point
                // should have completely detached objects from the transaction (i.e. serialization has occurred)
                // so a new one should not be opened on the flush down the netty pipeline
                ctx.writeAndFlush(frame);
            }
        } else {
            // don't keep triggering this warning over and over again for the same request
            if (!warnOnce) {
                logger.warn(
                        "Pausing response writing as writeBufferHighWaterMark exceeded on {} - writing will continue once client has caught up",
                        msg);
                warnOnce = true;
            }

            // since the client is lagging we can hold here for a period of time for the client to catch up.
            // this isn't blocking the IO thread - just a worker.
            TimeUnit.MILLISECONDS.sleep(10);
        }

        stopWatch.split();
        if (stopWatch.getSplitTime() > settings.serializedResponseTimeout) {
            final String timeoutMsg = String.format(
                    "Serialization of the entire response exceeded the 'serializeResponseTimeout' setting %s",
                    warnOnce ? "[Gremlin Server paused writes to client as messages were not being consumed quickly enough]"
                            : "");
            throw new TimeoutException(timeoutMsg.trim());
        }

        stopWatch.unsplit();
    }

    stopWatch.stop();
}

From source file:com.zia.freshdocs.widget.adapter.CMISAdapter.java

/**
 * Download the content for the given NodeRef
 * /*from   ww w .  ja  v a 2 s  . c om*/
 * @param ref
 * @param handler
 */
protected void downloadContent(final NodeRef ref, final Handler handler) {
    startProgressDlg(false);
    mProgressDlg.setMax(Long.valueOf(ref.getContentLength()).intValue());

    mDlThread = new ChildDownloadThread(handler, new Downloadable() {
        public Object execute() {
            File f = null;

            try {
                CMISApplication app = (CMISApplication) getContext().getApplicationContext();
                URL url = new URL(ref.getContent());
                String name = ref.getName();
                long fileSize = ref.getContentLength();
                f = app.getFile(name, fileSize);

                if (f != null && f.length() != fileSize) {
                    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

                    FileOutputStream fos = new FileOutputStream(f);
                    InputStream is = mCmis.get(url.getPath());

                    byte[] buffer = new byte[BUF_SIZE];
                    int len = is.read(buffer);
                    int total = len;
                    Message msg = null;
                    Bundle b = null;

                    while (len != -1) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("progress", total);
                        msg.setData(b);
                        handler.sendMessage(msg);

                        fos.write(buffer, 0, len);
                        len = is.read(buffer);
                        total += len;

                        if (Thread.interrupted()) {
                            fos.close();
                            f = null;
                            throw new InterruptedException();
                        }
                    }

                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                Log.e(CMISAdapter.class.getSimpleName(), "", e);
            }

            return f;
        }
    });
    mDlThread.start();
}

From source file:net.sf.jasperreports.engine.fill.BaseReportFiller.java

protected void checkInterrupted() {
    if (Thread.interrupted()) {
        threadInterrupted = true;//from  w w w. j a  v  a 2 s  .  c  om
    }

    if (isInterrupted()) {
        if (log.isDebugEnabled()) {
            log.debug("Fill " + fillerId + ": interrupting");
        }

        throw new JRFillInterruptedException();
    }
}

From source file:com.btoddb.fastpersitentqueue.InMemorySegmentMgr.java

public void shutdown() {
    shutdownInProgress = true;/*from www  .  j ava 2s.  c  o m*/

    // wait until all segments are either READY or OFFLINE
    // then serialize the READYs
    for (MemorySegment segment : segments) {
        while (segment.getStatus() != MemorySegment.Status.READY
                && segment.getStatus() != MemorySegment.Status.OFFLINE) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // ignore
                Thread.interrupted();
            }
        }

        if (segment.getStatus() == MemorySegment.Status.READY) {
            pageSegmentToDisk(segment);
        }
    }

    segments.clear();
    numberOfEntries.set(0);

    serializerExecSrvc.shutdown();
    try {
        serializerExecSrvc.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // ignore
        Thread.interrupted();
    }
    if (!serializerExecSrvc.isShutdown()) {
        serializerExecSrvc.shutdownNow();
    }

    cleanupExecSrvc.shutdown();
    try {
        cleanupExecSrvc.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // ignore
        Thread.interrupted();
    }
    if (!cleanupExecSrvc.isShutdown()) {
        cleanupExecSrvc.shutdownNow();
    }

    segmentSerializer.shutdown();
}

From source file:gda.data.scan.datawriter.NexusDataWriter.java

private void checkForThreadInterrupt() throws InterruptedException {
    if (Thread.interrupted()) {
        Thread.currentThread().interrupt();
        throw new InterruptedException();
    }/*from www . j av  a2s  .c o  m*/
}

From source file:net.sf.jasperreports.engine.export.JRXmlExporter.java

protected void exportReportToStream(Writer writer) throws JRException, IOException {
    version = JRPropertiesUtil.getInstance(jasperReportsContext).getProperty(jasperPrint,
            JRXmlBaseWriter.PROPERTY_REPORT_VERSION);

    xmlWriter = new JRXmlWriteHelper(writer);

    xmlWriter.writeProlog(encoding);/*from   ww  w  .  j a  va2 s.  com*/

    xmlWriter.startElement(JRXmlConstants.ELEMENT_jasperPrint, getNamespace());
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, jasperPrint.getName());
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_pageWidth, jasperPrint.getPageWidth());
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_pageHeight, jasperPrint.getPageHeight());
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_topMargin, jasperPrint.getTopMargin());
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_leftMargin, jasperPrint.getLeftMargin());
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_bottomMargin, jasperPrint.getBottomMargin());
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_rightMargin, jasperPrint.getRightMargin());
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_orientation, jasperPrint.getOrientationValue(),
            OrientationEnum.PORTRAIT);
    xmlWriter.addAttribute(JRXmlConstants.ATTRIBUTE_formatFactoryClass, jasperPrint.getFormatFactoryClass());
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_locale, jasperPrint.getLocaleCode());
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_timezone, jasperPrint.getTimeZoneId());

    //FIXME this leads to property duplication if a JasperPrint is loaded
    //from a *.jrpxml and exported back to xml
    xmlWriter.startElement(JRXmlConstants.ELEMENT_property);
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, PROPERTY_START_PAGE_INDEX);
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_value, String.valueOf(startPageIndex));
    xmlWriter.closeElement();

    xmlWriter.startElement(JRXmlConstants.ELEMENT_property);
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, PROPERTY_END_PAGE_INDEX);
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_value, String.valueOf(endPageIndex));
    xmlWriter.closeElement();

    xmlWriter.startElement(JRXmlConstants.ELEMENT_property); //FIXME make this configurable?
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, PROPERTY_PAGE_COUNT);
    xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_value,
            jasperPrint.getPages() == null ? null : String.valueOf(jasperPrint.getPages().size()));
    xmlWriter.closeElement();

    exportProperties(jasperPrint);

    JROrigin[] origins = jasperPrint.getOrigins();
    if (origins != null && origins.length > 0) {
        for (int i = 0; i < origins.length; i++) {
            exportOrigin(origins[i]);
        }
    }

    JRStyle[] styles = jasperPrint.getStyles();
    if (styles != null && styles.length > 0) {
        for (int i = 0; i < styles.length; i++) {
            stylesMap.put(styles[i].getName(), styles[i]);
            exportStyle(styles[i]);
        }
    }

    List<JRPrintPage> pages = jasperPrint.getPages();
    if (pages != null && pages.size() > 0) {
        JRPrintPage page = null;
        for (int i = startPageIndex; i <= endPageIndex; i++) {
            if (Thread.interrupted()) {
                throw new JRException("Current thread interrupted.");
            }

            page = pages.get(i);

            /*   */
            exportPage(page);
        }
    }

    xmlWriter.closeElement();

    writer.flush();
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataBlockScanner.java

/** returns false if the process was interrupted
 * because the thread is marked to exit.
 *///from  w  ww .  j av a 2 s  .c om
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();
    }

    try {
        // 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);
            }
        }
    } finally {
        IOUtils.closeStream(logReader);
    }

    /* 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;
}