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:org.apache.drill.optiq.EnumerableDrill.java

@Override
public Enumerator<E> enumerator() {
    // TODO: use a completion service from the container
    final ExecutorCompletionService<Collection<RunOutcome>> service = new ExecutorCompletionService<Collection<RunOutcome>>(
            new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(10)));

    // Run the plan using an executor. It runs in a different thread, writing
    // results to our queue.
    ////from ww w.  j av  a2  s .  c  om
    // TODO: use the result of task, and check for exceptions
    final Future<Collection<RunOutcome>> task = runPlan(service);

    return new Enumerator<E>() {
        private E current;

        @Override
        public E current() {
            return current;
        }

        @Override
        public boolean moveNext() {
            try {
                Object o = queue.take();
                if (o instanceof RunOutcome.OutcomeType) {
                    switch ((RunOutcome.OutcomeType) o) {
                    case SUCCESS:
                        return false; // end of data
                    case CANCELED:
                        throw new RuntimeException("canceled");
                    case FAILED:
                    default:
                        throw new RuntimeException("failed");
                    }
                } else {
                    current = (E) parseJson((byte[]) o);
                    return true;
                }
            } catch (InterruptedException e) {
                Thread.interrupted();
                throw new RuntimeException(e);
            }
        }

        @Override
        public void reset() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.tomitribe.tribestream.registryng.test.Registry.java

public <T> T withRetries(final Supplier<T> task, final String... description) {
    Throwable lastErr = null;/*w  w  w. j  ava 2  s .c  om*/
    final int max = Integer.getInteger("test.registry.retries", 3);
    final Client client = ClientBuilder.newClient();
    try {
        for (int i = 0; i < max; i++) {
            assertEquals(Response.Status.OK.getStatusCode(),
                    client.target("http://localhost:" + System.getProperty("test.elasticsearch.port"))
                            .path("_refresh").request(MediaType.APPLICATION_JSON_TYPE).get().getStatus());
            try {
                return task.get();
            } catch (final Throwable error) {
                lastErr = error;
                if (i % 3 == 0) {
                    Logger.getLogger(Registry.class.getName())
                            .info("Retry cause (" + (i + 1) + "/" + max + ")"
                                    + ofNullable(description).filter(d -> d.length >= 1)
                                            .map(d -> Stream.of(d).collect(joining(" "))).orElse("")
                                    + ": " + error.getMessage());
                }
                try {
                    sleep(1000);
                } catch (final InterruptedException e) {
                    Thread.interrupted();
                    fail("quitting");
                }
            }
        }
    } finally {
        client.close();
    }
    if (RuntimeException.class.isInstance(lastErr)) {
        throw RuntimeException.class.cast(lastErr);
    }
    throw new IllegalStateException(lastErr);
}

From source file:org.marketcetera.util.except.ExceptUtilsTest.java

@Test
public void interruptionMessageNestedThrow() {
    CloneNotSupportedException nested = new CloneNotSupportedException();
    Thread.currentThread().interrupt();
    try {//www  .  j  a  v a2s .  c o m
        ExceptUtils.checkInterruption(nested, TEST_MSG_1);
        fail();
    } catch (InterruptedException ex) {
        assertTrue(Thread.interrupted());
        assertEquals(TEST_MSG_1, ex.getMessage());
        assertEquals(nested, ex.getCause());
    }
}

From source file:org.apache.jackrabbit.oak.plugins.document.persistentCache.CacheTest.java

@Test
public void interrupt() throws Exception {
    FileUtils.deleteDirectory(new File("target/cacheTest"));
    PersistentCache cache = new PersistentCache("target/cacheTest,size=1,-compress");
    try {/*from   w  w w.  j  av a2s  .  c  o m*/
        CacheMap<String, String> m1 = cache.openMap(0, "m1", null);
        CacheMap<String, String> m2 = cache.openMap(0, "test", null);

        // the cache file was opened once so far
        assertEquals(1, cache.getOpenCount());

        // we store 20 mb of data, to ensure not all data is kept in memory
        String largeString = new String(new char[1024 * 1024]);
        int count = 10;
        for (int i = 0; i < count; i++) {
            m1.put("x" + i, largeString);
            m2.put("y" + i, largeString);
        }

        // interrupt the thread, which will cause the FileChannel
        // to be closed in the next read operation
        Thread.currentThread().interrupt();

        // this will force at least one read operation,
        // which should re-open the maps
        for (int i = 0; i < count; i++) {
            m1.get("x" + i);
            m2.get("y" + i);
        }

        assertEquals(2, cache.getOpenCount());

        // re-opening will clear the interrupt flag
        assertFalse(Thread.interrupted());

    } finally {
        cache.close();
    }
}

From source file:org.apache.excalibur.event.command.AbstractThreadManager.java

/**
 * The code that is run in the background to manage the ThreadPool and the
 * EventPipelines//from   www. j  a v a2 s .  co  m
 */
public void run() {
    while (!m_done) {
        Iterator i = m_pipelines.values().iterator();

        while (i.hasNext()) {
            PipelineRunner nextRunner = (PipelineRunner) i.next();

            try {
                m_executor.execute(nextRunner);
            } catch (Exception e) {
                if (getLogger().isErrorEnabled()) {
                    getLogger().error("Caught exception in ThreadManager management thread", e);
                }
            }
        }

        if (!m_done) {
            try {
                Thread.sleep(m_sleepTime);
            } catch (InterruptedException e) {
                Thread.interrupted();
            }
        }
    }
}

From source file:org.codehaus.wadi.group.impl.AbstractDispatcher.java

public Collection attemptMultiRendezVous(Quipu rv, long timeout) throws MessageExchangeException {
    Collection response = null;/*from   www .j ava 2  s .com*/
    try {
        do {
            try {
                long startTime = System.currentTimeMillis();
                if (rv.waitFor(timeout)) {
                    response = rv.getResults();
                    long elapsedTime = System.currentTimeMillis() - startTime;
                    if (log.isTraceEnabled()) {
                        log.trace("successful message exchange within timeframe (" + elapsedTime + "<" + timeout
                                + " millis) {" + rv + "}");
                    }
                } else {
                    log.debug("unsuccessful message exchange within timeframe (" + timeout + " millis) {" + rv
                            + "}", new Exception());
                }
            } catch (InterruptedException e) {
                log.debug("waiting for response - interruption ignored");
            } catch (QuipuException e) {
                throw new MessageExchangeException(e);
            }
        } while (Thread.interrupted());
    } finally {
        rvMap.remove(rv.getCorrelationId());
    }
    if (null == response) {
        throw new MessageExchangeException("No correlated messages received within [" + timeout + "]ms");
    }
    return response;
}

From source file:org.jumpmind.symmetric.job.AbstractJob.java

public boolean invoke(boolean force) {
    IParameterService parameterService = engine.getParameterService();
    boolean ran = false;
    try {//from w ww. j  av  a2  s.c o m
        if (engine == null) {
            log.info("Could not find a reference to the SymmetricEngine from {}", jobName);
        } else {
            if (!Thread.interrupted()) {
                MDC.put("engineName", engine.getEngineName());
                if (engine.isStarted()) {
                    if (!paused || force) {
                        if (!running) {
                            running = true;
                            synchronized (this) {
                                ran = true;
                                long startTime = System.currentTimeMillis();
                                try {
                                    if (!requiresRegistration || (requiresRegistration
                                            && engine.getRegistrationService().isRegisteredWithServer())) {
                                        hasNotRegisteredMessageBeenLogged = false;
                                        if (parameterService.is(ParameterConstants.SYNCHRONIZE_ALL_JOBS)) {
                                            synchronized (AbstractJob.class) {
                                                doJob(force);
                                            }
                                        } else {
                                            doJob(force);
                                        }
                                    } else {
                                        if (!hasNotRegisteredMessageBeenLogged) {
                                            log.info(
                                                    "Did not run the {} job because the engine is not registered.",
                                                    getName());
                                            hasNotRegisteredMessageBeenLogged = true;
                                        }
                                    }
                                } finally {
                                    lastFinishTime = new Date();
                                    long endTime = System.currentTimeMillis();
                                    lastExecutionTimeInMs = endTime - startTime;
                                    totalExecutionTimeInMs += lastExecutionTimeInMs;
                                    if (lastExecutionTimeInMs > Constants.LONG_OPERATION_THRESHOLD) {
                                        engine.getStatisticManager().addJobStats(jobName, startTime, endTime,
                                                0);
                                    }
                                    numberOfRuns++;
                                    running = false;
                                }
                            }
                        }
                    }
                } else {
                    log.info("The engine is not currently started.");
                }
            } else {
                log.warn(
                        "This thread was interrupted.  Not executing the job until the interrupted status has cleared");
            }
        }
    } catch (final Throwable ex) {
        log.error("", ex);
    }

    return ran;
}

From source file:org.archive.io.RecordingInputStream.java

public void readToEndOfContent(long contentLength) throws IOException, InterruptedException {
    // Check we're open before proceeding.
    if (!isOpen()) {
        // TODO: should this be a noisier exception-raising error? 
        return;//from w w  w .  j a  v  a 2  s.c om
    }

    long totalBytes = recordingOutputStream.position - recordingOutputStream.getMessageBodyBegin();
    long bytesRead = -1L;
    long maxToRead = -1;
    while (contentLength <= 0 || totalBytes < contentLength) {
        try {
            // read no more than soft max
            maxToRead = (contentLength <= 0) ? drainBuffer.length
                    : Math.min(drainBuffer.length, contentLength - totalBytes);
            // nor more than hard max
            maxToRead = Math.min(maxToRead, recordingOutputStream.getRemainingLength());
            // but always at least 1 (to trigger hard max exception) XXX wtf is this?
            maxToRead = Math.max(maxToRead, 1);

            bytesRead = read(drainBuffer, 0, (int) maxToRead);
            if (bytesRead == -1) {
                break;
            }
            totalBytes += bytesRead;

            if (Thread.interrupted()) {
                throw new InterruptedException("Interrupted during IO");
            }
        } catch (SocketTimeoutException e) {
            // A socket timeout is just a transient problem, meaning
            // nothing was available in the configured  timeout period,
            // but something else might become available later.
            // Take this opportunity to check the overall 
            // timeout (below).  One reason for this timeout is 
            // servers that keep up the connection, 'keep-alive', even
            // though we asked them to not keep the connection open.
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "socket timeout", e);
            }
            // check for interrupt
            if (Thread.interrupted()) {
                throw new InterruptedException("Interrupted during IO");
            }
            // check for overall timeout
            recordingOutputStream.checkLimits();
        } catch (SocketException se) {
            throw se;
        } catch (NullPointerException e) {
            // [ 896757 ] NPEs in Andy's Th-Fri Crawl.
            // A crawl was showing NPE's in this part of the code but can
            // not reproduce.  Adding this rethrowing catch block w/
            // diagnostics to help should we come across the problem in the
            // future.
            throw new NullPointerException(
                    "Stream " + this.in + ", " + e.getMessage() + " " + Thread.currentThread().getName());
        }
    }
}

From source file:org.apache.hadoop.hbase.thrift.TBoundedThreadPoolServer.java

public void serve() {
    try {//from   w  w w . j  av a2s  .  c  o m
        serverTransport_.listen();
    } catch (TTransportException ttx) {
        LOG.error("Error occurred during listening.", ttx);
        return;
    }

    Runtime.getRuntime().addShutdownHook(new Thread(getClass().getSimpleName() + "-shutdown-hook") {
        @Override
        public void run() {
            TBoundedThreadPoolServer.this.stop();
        }
    });

    stopped = false;
    while (!stopped && !Thread.interrupted()) {
        TTransport client = null;
        try {
            client = serverTransport_.accept();
        } catch (TTransportException ttx) {
            if (!stopped) {
                LOG.warn("Transport error when accepting message", ttx);
                continue;
            } else {
                // The server has been stopped
                break;
            }
        }

        ClientConnnection command = new ClientConnnection(client);
        try {
            executorService.execute(command);
        } catch (RejectedExecutionException rex) {
            if (client.getClass() == TSocket.class) {
                // We expect the client to be TSocket.
                LOG.warn(QUEUE_FULL_MSG + " from " + ((TSocket) client).getSocket().getRemoteSocketAddress());
            } else {
                LOG.warn(QUEUE_FULL_MSG, rex);
            }
            client.close();
        }
    }

    shutdownServer();
}

From source file:com.granita.contacticloudsync.syncadapter.ContactsSyncManager.java

@Override
protected void downloadRemote() throws IOException, HttpException, DavException, ContactsStorageException {
    log.info("Downloading " + toDownload.size() + " contacts (" + MAX_MULTIGET + " at once)");

    // prepare downloader which may be used to download external resource like contact photos
    Contact.Downloader downloader = new ResourceDownloader(httpClient, collectionURL);

    // download new/updated VCards from server
    for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]),
            MAX_MULTIGET)) {//w  ww .java  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/vcard;version=4.0, text/vcard;charset=utf-8;q=0.8, text/vcard;q=0.5");
            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();
            processVCard(remote.fileName(), eTag, stream, charset, downloader);

        } else {
            // multiple contacts, use multi-get
            List<HttpUrl> urls = new LinkedList<>();
            for (DavResource remote : bunch)
                urls.add(remote.location);
            davAddressBook().multiget(urls.toArray(new HttpUrl[urls.size()]), hasVCard4);

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

                AddressData addressData = (AddressData) remote.properties.get(AddressData.NAME);
                if (addressData == null || addressData.vCard == null)
                    throw new DavException("Received multi-get response without address data");

                @Cleanup
                InputStream stream = new ByteArrayInputStream(addressData.vCard.getBytes());
                processVCard(remote.fileName(), eTag, stream, charset, downloader);
            }
        }
    }
}