Example usage for java.lang Thread interrupt

List of usage examples for java.lang Thread interrupt

Introduction

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

Prototype

public void interrupt() 

Source Link

Document

Interrupts this thread.

Usage

From source file:org.echocat.jomon.net.dns.DnsServer.java

@Override
public void close() throws Exception {
    synchronized (this) {
        _closed = true;/*from  w ww  . ja  va 2  s  .  c o m*/
        synchronized (_closeables) {
            for (final Closeable closeable : _closeables) {
                closeQuietly(closeable);
            }
        }
        for (final Thread thread : _threads) {
            do {
                thread.interrupt();
                try {
                    thread.join(10);
                } catch (final InterruptedException ignored) {
                    LOG.info("Got interrupted and could not wait for end of '" + thread + "'.");
                    currentThread().interrupt();
                }
            } while (!currentThread().isInterrupted() && thread.isAlive());
        }
    }
}

From source file:org.apache.xmlrpc.WebServer.java

/**
 * Stop listening on the server port.  Shutting down our {@link
 * #listener} effectively breaks it out of its {@link #run()}
 * loop.//from  ww  w. j a  va  2 s . com
 *
 * @see #run()
 */
public synchronized void shutdown() {
    // Stop accepting client connections
    if (listener != null) {
        Thread l = listener;
        listener = null;
        l.interrupt();
    }
}

From source file:org.springframework.integration.channel.QueueChannelTests.java

@Test
public void testBlockingReceiveWithNoTimeout() throws Exception {
    final QueueChannel channel = new QueueChannel();
    final AtomicBoolean receiveInterrupted = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread(new Runnable() {
        @Override/*from   ww  w  .  j a va 2 s .c om*/
        public void run() {
            Message<?> message = channel.receive();
            receiveInterrupted.set(true);
            assertTrue(message == null);
            latch.countDown();
        }
    });
    t.start();
    assertFalse(receiveInterrupted.get());
    t.interrupt();
    latch.await();
    assertTrue(receiveInterrupted.get());
}

From source file:org.codelibs.fess.crawler.extractor.impl.PdfExtractor.java

@Override
public ExtractData getText(final InputStream in, final Map<String, String> params) {
    if (in == null) {
        throw new CrawlerSystemException("The inputstream is null.");
    }//from  w  ww  .  j  a v  a  2  s . co m

    synchronized (pdfBoxLockObj) {
        final String password = getPassword(params);
        try (PDDocument document = PDDocument.load(in, password)) {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final Writer output = new OutputStreamWriter(baos, encoding);
            final PDFTextStripper stripper = new PDFTextStripper();
            final AtomicBoolean done = new AtomicBoolean(false);
            final PDDocument doc = document;
            final Set<Exception> exceptionSet = new HashSet<>();
            final Thread task = new Thread(() -> {
                try {
                    stripper.writeText(doc, output);
                } catch (final Exception e) {
                    exceptionSet.add(e);
                } finally {
                    done.set(true);
                }
            });
            task.setDaemon(true);
            task.start();
            task.join(timeout);
            if (!done.get()) {
                for (int i = 0; i < 100 && !done.get(); i++) {
                    task.interrupt();
                    Thread.sleep(50);
                }
                throw new ExtractException("PDFBox process cannot finish in " + timeout + " sec.");
            } else if (!exceptionSet.isEmpty()) {
                throw exceptionSet.iterator().next();
            }
            output.flush();
            final ExtractData extractData = new ExtractData(baos.toString(encoding));
            extractMetadata(document, extractData);
            return extractData;
        } catch (final Exception e) {
            throw new ExtractException(e);
        }
    }
}

From source file:org.springframework.integration.channel.QueueChannelTests.java

@Test
public void testBlockingReceiveWithTimeout() throws Exception {
    final QueueChannel channel = new QueueChannel();
    final AtomicBoolean receiveInterrupted = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread(new Runnable() {
        @Override/*w w w. ja  v a  2 s .  c  o  m*/
        public void run() {
            Message<?> message = channel.receive(10000);
            receiveInterrupted.set(true);
            assertTrue(message == null);
            latch.countDown();
        }
    });
    t.start();
    assertFalse(receiveInterrupted.get());
    t.interrupt();
    latch.await();
    assertTrue(receiveInterrupted.get());
}

From source file:eu.stratosphere.pact.testing.MockTaskManager.java

@Override
public TaskCancelResult cancelTask(final ExecutionVertexID id) throws IOException {

    RuntimeEnvironment environment = this.runningTasks.get(id);
    final Thread executingThread = environment.getExecutingThread();

    this.finishedTasks.put(id, environment);
    this.observers.get(environment).cancel();
    // Request user code to shut down
    try {/*from  w w  w .j  a va 2  s .c  om*/
        final AbstractInvokable invokable = environment.getInvokable();
        if (invokable != null)
            invokable.cancel();
        executingThread.interrupt();
    } catch (Throwable e) {
        LOG.error(StringUtils.stringifyException(e));
    }

    return new TaskCancelResult(id, TaskCancelResult.ReturnCode.SUCCESS);
}

From source file:org.apache.cloud.rdf.web.sail.RdfController.java

@RequestMapping(value = "/queryrdf", method = { RequestMethod.GET, RequestMethod.POST })
public void queryRdf(@RequestParam("query") final String query,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, required = false) String auth,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_CV, required = false) final String vis,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_INFER, required = false) final String infer,
        @RequestParam(value = "nullout", required = false) final String nullout,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_RESULT_FORMAT, required = false) final String emit,
        @RequestParam(value = "padding", required = false) final String padding,
        @RequestParam(value = "callback", required = false) final String callback,
        final HttpServletRequest request, final HttpServletResponse response) {
    // WARNING: if you add to the above request variables,
    // Be sure to validate and encode since they come from the outside and could contain odd damaging character sequences.
    SailRepositoryConnection conn = null;
    final Thread queryThread = Thread.currentThread();
    auth = StringUtils.arrayToCommaDelimitedString(provider.getUserAuths(request));
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override//from w  w  w  . j a  v  a 2s. c o  m
        public void run() {
            log.debug("interrupting");
            queryThread.interrupt();

        }
    }, QUERY_TIME_OUT_SECONDS * 1000);

    try {
        final ServletOutputStream os = response.getOutputStream();
        conn = repository.getConnection();

        final Boolean isBlankQuery = StringUtils.isEmpty(query);
        final ParsedOperation operation = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, query, null);

        final Boolean requestedCallback = !StringUtils.isEmpty(callback);
        final Boolean requestedFormat = !StringUtils.isEmpty(emit);

        if (!isBlankQuery) {
            if (operation instanceof ParsedGraphQuery) {
                // Perform Graph Query
                final RDFHandler handler = new RDFXMLWriter(os);
                response.setContentType("text/xml");
                performGraphQuery(query, conn, auth, infer, nullout, handler);
            } else if (operation instanceof ParsedTupleQuery) {
                // Perform Tuple Query
                TupleQueryResultHandler handler;

                if (requestedFormat && emit.equalsIgnoreCase("json")) {
                    handler = new SPARQLResultsJSONWriter(os);
                    response.setContentType("application/json");
                } else {
                    handler = new SPARQLResultsXMLWriter(os);
                    response.setContentType("text/xml");
                }

                performQuery(query, conn, auth, infer, nullout, handler);
            } else if (operation instanceof ParsedUpdate) {
                // Perform Update Query
                performUpdate(query, conn, os, infer, vis);
            } else {
                throw new MalformedQueryException("Cannot process query. Query type not supported.");
            }
        }

        if (requestedCallback) {
            os.print(")");
        }
    } catch (final Exception e) {
        log.error("Error running query", e);
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (final RepositoryException e) {
                log.error("Error closing connection", e);
            }
        }
    }

    timer.cancel();
}

From source file:ResourcePool.java

/**
 * Adds a resource to this set. After the resource is added, it is treated
 * identically to any other resource in this pool. In particular, if this
 * resource pool is managed by a creator, the new resource may be destroyed
 * by the pool if the pool's maximum size is reduced to make the pool too
 * large.//from ww w .j a v  a 2 s.  c om
 * 
 * @param resource
 *            The resource to make available to the pool
 */
public void addResource(T resource) {
    if (isClosed)
        throw new IllegalStateException("This resource pool is closed");
    Thread waiting = null;
    theLock.lock();
    try {
        if (!theWaitingThreads.isEmpty() || !isClosed) {
            theAvailableResources.add(resource);
            if (!theWaitingThreads.isEmpty())
                waiting = theWaitingThreads.removeFirst();
        }
    } finally {
        theLock.unlock();
    }
    if (waiting != null)
        waiting.interrupt();
}

From source file:com.jogden.spunkycharts.pricebyvolumechart.PriceByVolumeChartFragmentAdapter.java

public void cleanUpAndUpdate() {
    _streamReady.set(false);/*from  w  w w  .  j  a  va 2 s .co  m*/
    for (Thread t : _activeThreads)
        t.interrupt();
    _clear(); /* leave display values */
    _highPrice = 0;
    _lowPrice = Float.MAX_VALUE;
    _highVolume = 0;
}

From source file:org.apache.hadoop.mapred.MiniMRCluster.java

/**
 * Shut down the servers./*from w  ww  . j a  va2 s  .  c  o  m*/
 */
public void shutdown() {
    try {
        waitTaskTrackers();
        for (int idx = 0; idx < numTaskTrackers; idx++) {
            TaskTrackerRunner taskTracker = taskTrackerList.get(idx);
            Thread taskTrackerThread = taskTrackerThreadList.get(idx);
            taskTracker.shutdown();
            taskTrackerThread.interrupt();
            try {
                taskTrackerThread.join();
            } catch (InterruptedException ex) {
                LOG.error("Problem shutting down task tracker", ex);
            }
        }
        stopJobTracker();
    } finally {
        File configDir = new File("build", "minimr");
        File siteFile = new File(configDir, "mapred-site.xml");
        siteFile.delete();
    }
}