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.zenoss.app.consumer.metric.impl.OpenTsdbWriter.java

void runUntilCanceled() throws InterruptedException {
    ExponentialBackOff backoffTracker = null;
    while (!isCanceled()) {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }//from ww w.  j  av  a  2  s . co m
        Collection<Metric> metrics = metricsQueue.poll(batchSize, maxIdleTime);
        log.debug("Back from polling metricsQueue. metrics.size = {}",
                null == metrics ? "null" : metrics.size());
        // Check to see if we should down this writer entirely.
        log.debug("Checking for shutdown. lastWorkTime = {}; maxIdleTime = {}; sum = {}; currentTime ={}",
                lastWorkTime, maxIdleTime, lastWorkTime + maxIdleTime, System.currentTimeMillis());
        if (isNullOrEmpty(metrics) && // No records could be read from the metrics queue
                lastWorkTime > 0 && // This thread has done work at least once
                maxIdleTime > 0 && // The max idle time is set to something meaningful
                System.currentTimeMillis() > lastWorkTime + maxIdleTime) // The max idle time has expired
        {
            log.info("Shutting down writer due to dearth of work");
            break;
        }

        /*
         * If all the conditions were not met for shutting this writer down,
         * we still might want to just abort this run if we didn't get any
         * data from the metrics queue
         */
        if (isNullOrEmpty(metrics)) {
            log.debug("No work to do, so checking again.");
            continue;
        }

        // We have some work to do, some process what we got from the metrics queue
        if (backoffTracker == null) {
            backoffTracker = createExponentialBackOff();
        }
        try {
            processBatch(metrics);
            backoffTracker.reset();
        } catch (NoSuchElementException e) {
            long backOff = this.minBackOff;
            try {
                backOff = backoffTracker.nextBackOffMillis();
            } catch (IOException e1) {
                // shouldn't happen but if it does we'll use the default backOff
                log.debug("caught IOException backing off tracker - should go to default backOff.");
            }
            if (ExponentialBackOff.STOP == backOff) {
                // We've reached the max amount of time to backoff, use max backoff
                backOff = backoffTracker.getMaxIntervalMillis();
                log.warn("Error getting OpenTsdbClient after {} ms: {}", backoffTracker.getElapsedTimeMillis(),
                        e.getMessage());
            }
            log.debug("Connection back off, sleeping {} ms", backOff);
            Thread.sleep(backOff);
        }
    }
    log.debug("work canceled.");
}

From source file:org.apache.phoenix.hbase.index.write.TestParalleIndexWriter.java

@SuppressWarnings({ "unchecked", "deprecation" })
@Test/*from  w  ww .ja va  2  s  .c  o m*/
public void testSynchronouslyCompletesAllWrites() throws Exception {
    LOG.info("Starting " + test.getTableNameString());
    LOG.info("Current thread is interrupted: " + Thread.interrupted());
    Abortable abort = new StubAbortable();
    Stoppable stop = Mockito.mock(Stoppable.class);
    ExecutorService exec = Executors.newFixedThreadPool(1);
    Map<ImmutableBytesPtr, HTableInterface> tables = new HashMap<ImmutableBytesPtr, HTableInterface>();
    FakeTableFactory factory = new FakeTableFactory(tables);

    ImmutableBytesPtr tableName = new ImmutableBytesPtr(this.test.getTableName());
    Put m = new Put(row);
    m.add(Bytes.toBytes("family"), Bytes.toBytes("qual"), null);
    Multimap<HTableInterfaceReference, Mutation> indexUpdates = ArrayListMultimap
            .<HTableInterfaceReference, Mutation>create();
    indexUpdates.put(new HTableInterfaceReference(tableName), m);

    HTableInterface table = Mockito.mock(HTableInterface.class);
    final boolean[] completed = new boolean[] { false };
    Mockito.when(table.batch(Mockito.anyList())).thenAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // just keep track that it was called
            completed[0] = true;
            return null;
        }
    });
    Mockito.when(table.getTableName()).thenReturn(test.getTableName());
    // add the table to the set of tables, so its returned to the writer
    tables.put(tableName, table);

    // setup the writer and failure policy
    ParallelWriterIndexCommitter writer = new ParallelWriterIndexCommitter(VersionInfo.getVersion());
    writer.setup(factory, exec, abort, stop, 1);
    writer.write(indexUpdates);
    assertTrue("Writer returned before the table batch completed! Likely a race condition tripped",
            completed[0]);
    writer.stop(this.test.getTableNameString() + " finished");
    assertTrue("Factory didn't get shutdown after writer#stop!", factory.shutdown);
    assertTrue("ExectorService isn't terminated after writer#stop!", exec.isShutdown());
}

From source file:net.technicpack.utilslib.ZipUtils.java

public static void unzipFile(File zip, File output, IZipFileFilter fileFilter, DownloadListener listener)
        throws IOException, InterruptedException {
    if (!zip.exists()) {
        Utils.getLogger().log(Level.SEVERE, "File to unzip does not exist: " + zip.getAbsolutePath());
        return;/*www .  ja v a  2  s .co  m*/
    }
    if (!output.exists()) {
        output.mkdirs();
    }

    ZipFile zipFile = new ZipFile(zip);
    int size = zipFile.size() + 1;
    int progress = 1;
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            if (Thread.interrupted())
                throw new InterruptedException();

            ZipEntry entry = null;

            try {
                entry = entries.nextElement();
            } catch (IllegalArgumentException ex) {
                //We must catch & rethrow as a zip exception because some crappy code in the zip lib will
                //throw illegal argument exceptions for malformed zips.
                throw new ZipException("IllegalArgumentException while parsing next element.");
            }

            if (!entry.getName().contains("../")
                    && (fileFilter == null || fileFilter.shouldExtract(entry.getName()))) {
                File outputFile = new File(output, entry.getName());

                if (outputFile.getParentFile() != null) {
                    outputFile.getParentFile().mkdirs();
                }

                if (!entry.isDirectory()) {
                    unzipEntry(zipFile, entry, outputFile);
                }
            }

            if (listener != null) {
                float totalProgress = (float) progress / (float) size;
                listener.stateChanged("Extracting " + entry.getName() + "...", totalProgress * 100.0f);
            }
            progress++;
        }
    } finally {
        zipFile.close();
    }
}

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

@Test
public void closeAlways() throws Exception {
    FileUtils.deleteDirectory(new File("target/cacheTest"));
    PersistentCache cache = new PersistentCache("target/cacheTest,manualCommit");
    CacheMap<String, String> map = cache.openMap(0, "test", null);
    // break the map by calling interrupt
    Thread.currentThread().interrupt();
    map.put("hello", "world");
    cache.close();/*  w  w  w.ja  v a 2s . c  o  m*/
    assertFalse(Thread.interrupted());
}

From source file:net.paoding.rose.web.instruction.ViewInstruction.java

@Override
public void doRender(Invocation inv) throws Exception {
    String name = resolvePlaceHolder(this.name, inv);
    ViewDispatcher viewResolver = getViewDispatcher(inv);
    String viewPath = getViewPath((InvocationBean) inv, name);
    if (viewPath != null) {
        HttpServletRequest request = inv.getRequest();
        HttpServletResponse response = inv.getResponse();
        ////from ww w .  j a va 2s .  c o m
        View view = viewResolver.resolveViewName(inv, viewPath, request.getLocale());

        if (!Thread.interrupted()) {
            inv.addModel(ROSE_INVOCATION, inv);
            view.render(inv.getModel().getAttributes(), request, response);
        } else {
            logger.info("interrupted");
        }
    }
}

From source file:annis.gui.resultfetch.ResultFetchJob.java

@Override
public void run() {
    WebResource subgraphRes = Helper.getAnnisWebResource().path("query/search/subgraph");

    // holds the ids of the matches.
    MatchGroup result;/*from   w w w.java 2 s. c om*/

    try {
        if (Thread.interrupted()) {
            return;
        }

        // set the the progress bar, for given the user some information about the loading process
        ui.accessSynchronously(new Runnable() {
            @Override
            public void run() {
                resultPanel.showMatchSearchInProgress(query);
            }
        });

        // get the matches
        result = futureMatches.get();

        // get the subgraph for each match, when the result is not empty
        if (result.getMatches().isEmpty()) {

            // check if thread was interrupted
            if (Thread.interrupted()) {
                return;
            }

            // nothing found, so inform the user about this.
            ui.access(new Runnable() {
                @Override
                public void run() {
                    resultPanel.showNoResult();
                }
            });
        } else {
            if (Thread.interrupted()) {
                return;
            }

            // since annis found something, inform the user that subgraphs are created
            ui.access(new Runnable() {
                @Override
                public void run() {
                    resultPanel.showSubgraphSearchInProgress(query, 0.0f);
                }
            });

            // prepare fetching subgraphs
            final int totalResultSize = result.getMatches().size();

            final BlockingQueue<SaltProject> queue = new ArrayBlockingQueue<>(totalResultSize);
            int current = 0;

            for (Match m : result.getMatches()) {
                if (Thread.interrupted()) {
                    return;
                }

                List<Match> subList = new LinkedList<>();
                subList.add(m);
                final SaltProject p = executeQuery(subgraphRes, new MatchGroup(subList), query.getLeftContext(),
                        query.getRightContext(), query.getSegmentation(), SubgraphFilter.all);

                queue.put(p);
                log.debug("added match {} to queue", current + 1);

                if (current == 0) {
                    PollControl.changePollingTime(ui, PollControl.DEFAULT_TIME);
                    ui.access(new Runnable() {
                        @Override
                        public void run() {
                            resultPanel.setQueryResultQueue(queue, query, totalResultSize);
                        }
                    });
                }

                if (Thread.interrupted()) {
                    return;
                }

                current++;
            }
        } // end if no results

    } catch (InterruptedException ex) {
        // just return
    } catch (final ExecutionException root) {
        ui.accessSynchronously(new Runnable() {
            @Override
            public void run() {
                if (resultPanel != null && resultPanel.getPaging() != null) {
                    PagingComponent paging = resultPanel.getPaging();
                    Throwable cause = root.getCause();
                    if (cause instanceof UniformInterfaceException) {
                        UniformInterfaceException ex = (UniformInterfaceException) cause;
                        if (ex.getResponse().getStatus() == 400) {
                            List<AqlParseError> errors = ex.getResponse()
                                    .getEntity(new GenericType<List<AqlParseError>>() {
                                    });
                            String errMsg = Joiner.on(" | ").join(errors);

                            paging.setInfo("parsing error: " + errMsg);
                        } else if (ex.getResponse().getStatus() == 504) {
                            paging.setInfo("Timeout: query exeuction took too long");
                        } else if (ex.getResponse().getStatus() == 403) {
                            paging.setInfo("Not authorized to query this corpus.");
                        } else {
                            paging.setInfo("unknown error: " + ex);
                        }
                    } else {
                        log.error("Unexcepted ExecutionException cause", root);
                    }

                    resultPanel.showFinishedSubgraphSearch();

                }
            }
        });
    } // end catch
}

From source file:info.pancancer.arch3.worker.WorkerHeartbeat.java

@Override
public void run() {

    Channel reportingChannel = null;
    try {//from  w ww  . j a  v a2 s .c  o m
        try {
            reportingChannel = Utilities.setupExchange(settings, this.queueName);
        } catch (IOException | TimeoutException | AlreadyClosedException e) {
            LOG.error("Exception caught! Queue channel could not be opened, waiting. Exception is: "
                    + e.getMessage(), e);
            // retry after a minute, do not die simply because the launcher is unavailable, it may come back
            Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.info("Caught interrupt signal, heartbeat shutting down.", e);
        return;
    }

    LOG.info("starting heartbeat thread, will send heartbeat message ever " + secondsDelay + " seconds.");
    while (!Thread.interrupted()) {
        // byte[] stdOut = this.getMessageBody().getBytes(StandardCharsets.UTF_8);
        try {
            try {
                Status heartbeatStatus = new Status();
                heartbeatStatus.setJobUuid(this.jobUuid);
                heartbeatStatus.setMessage("job is running; IP address: " + networkID);
                heartbeatStatus.setState(StatusState.RUNNING);
                heartbeatStatus.setType(Utilities.JOB_MESSAGE_TYPE);
                heartbeatStatus.setVmUuid(this.vmUuid);
                heartbeatStatus.setIpAddress(networkID);

                // String stdOut = this.statusSource.getStdOut();
                Lock lock = new ReentrantLock();
                lock.lock();
                String stdOut = this.statusSource.getStdOut(stdoutSnipSize);
                String stdErr = this.statusSource.getStdErr();
                lock.unlock();
                heartbeatStatus.setStdout(stdOut);
                heartbeatStatus.setStderr(stdErr);
                String heartBeatMessage = heartbeatStatus.toJSON();
                LOG.debug("Sending heartbeat message to " + queueName + ", with body: " + heartBeatMessage);
                reportingChannel.basicPublish(queueName, queueName, MessageProperties.PERSISTENT_TEXT_PLAIN,
                        heartBeatMessage.getBytes(StandardCharsets.UTF_8));
                reportingChannel.waitForConfirms();

                Thread.sleep((long) (secondsDelay * MILLISECONDS_PER_SECOND));
            } catch (IOException | AlreadyClosedException e) {
                LOG.error("IOException caught! Message may not have been published. Exception is: "
                        + e.getMessage(), e);
                // retry after a minute, do not die simply because the launcher is unavailable, it may come back
                Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
            }
        } catch (InterruptedException e) {
            LOG.info("Heartbeat shutting down.");
            if (reportingChannel.getConnection().isOpen()) {
                try {
                    reportingChannel.getConnection().close();
                } catch (IOException e1) {
                    LOG.error("Error closing reportingChannel connection: " + e1.getMessage(), e1);
                }
            }
            if (reportingChannel.isOpen()) {
                try {
                    reportingChannel.close();
                } catch (IOException e1) {
                    LOG.error("Error (IOException) closing reportingChannel: " + e1.getMessage(), e1);
                } catch (TimeoutException e1) {
                    LOG.error("Error (TimeoutException) closing reportingChannel: " + e1.getMessage(), e1);
                }
            }
            LOG.debug("reporting channel open: " + reportingChannel.isOpen());
            LOG.debug("reporting channel connection open: " + reportingChannel.getConnection().isOpen());

            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.gnizr.core.robot.rss.CrawlRssFeed.java

public void shutdown() {
    try {/*from w w w .j  a v  a 2 s.c om*/
        System.out.println("CrawlRssFeed shutdown.");
        List<Runnable> activeTasks = saveBookmarkEntriesExecutor.shutdownNow();
        System.out.println("After shutdown. Number of active tasks = " + activeTasks.size());
        if (activeTasks.size() > 0) {
            System.out.println("calling Thread.interrputed");
            Thread.interrupted();
            System.out.println("done calling Thread.interrputed");
        }
    } catch (Exception e) {

    }
    if (threadPoolTaskExecutor != null) {
        try {
            threadPoolTaskExecutor.shutdown();
        } catch (Exception e) {

        }
    }

}

From source file:org.covito.kit.cache.CacheTest.java

@Test
public void testAutoSave() {

    System.out.println(CacheManager.getCacheNames());

    final Cache<String, String> autoRefresh = CacheManager.getCache("autoRefresh");

    new Thread(new Runnable() {
        @Override/*  www .  j  a  v  a  2 s. c  o  m*/
        public void run() {
            while (true) {
                System.out.println(autoRefresh.get("A"));
                ;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
    ;
    Thread.interrupted();
}

From source file:org.mule.modules.cookbook.CookbookConnector.java

/**
 * Description for getRecentlyAddedSource
 *
 * {@sample.xml ../../../doc/cook-book-connector.xml.sample cook-book:getRecentlyAddedSource}
 *
 * @param callback//from ww w.j a  va 2 s.  c  o  m
 *            The callback that will hook the result into mule event.
 * @throws Exception
 *             When the source fails.
 */
@OAuthProtected
@Source(sourceStrategy = SourceStrategy.POLLING, pollingPeriod = 10000)
public void getRecentlyAddedSource(final SourceCallback callback) throws Exception {

    if (this.getConfig().getClient() != null) {
        // Every 5 seconds our callback will be executed
        this.getConfig().getClient().getRecentlyAdded(new ICookbookCallback() {

            @Override
            public void execute(List<Recipe> recipes) throws Exception {
                callback.process(recipes);
            }
        });

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }
}