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:io.druid.query.lookup.LookupReferencesManager.java

@LifecycleStart
public void start() {
    if (!lifecycleLock.canStart()) {
        throw new ISE("can't start.");
    }//from  w  w w. ja v  a 2s  .  co  m
    try {
        LOG.info("LookupReferencesManager is starting.");
        loadAllLookupsAndInitStateRef();
        if (!testMode) {
            mainThread = Execs.makeThread("LookupReferencesManager-MainThread", () -> {
                try {
                    if (!lifecycleLock.awaitStarted()) {
                        LOG.error("WTF! lifecycle not started, lookup update notices will not be handled.");
                        return;
                    }

                    while (!Thread.interrupted() && lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)) {
                        try {
                            handlePendingNotices();
                            LockSupport.parkNanos(LookupReferencesManager.this, TimeUnit.MINUTES.toNanos(1));
                        } catch (Throwable t) {
                            LOG.makeAlert(t, "Error occured while lookup notice handling.").emit();
                        }
                    }
                } catch (Throwable t) {
                    LOG.error(t,
                            "Error while waiting for lifecycle start. lookup updates notices will not be handled");
                } finally {
                    LOG.info("Lookup Management loop exited, Lookup notices are not handled anymore.");
                }
            }, true);

            mainThread.start();
        }

        LOG.info("LookupReferencesManager is started.");
        lifecycleLock.started();
    } finally {
        lifecycleLock.exitStart();
    }
}

From source file:com.giovanniterlingen.windesheim.view.Fragments.ChooseScheduleFragment.java

private synchronized ArrayList<ScheduleItem> buildClassArray(JSONArray jsonArray) {
    ArrayList<ScheduleItem> scheduleItems = new ArrayList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        try {//  ww w.  ja va 2 s. c  om
            if (Thread.interrupted()) {
                return null;
            }
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            scheduleItems.add(new ScheduleItem(jsonObject.getInt("id"),
                    jsonObject.getString("name") + " - " + jsonObject.getString("longName")));
        } catch (JSONException e) {
            alertConnectionProblem();
            return null;
        }
    }
    return scheduleItems;
}

From source file:net.sf.jasperreports.engine.print.JRPrinterAWT.java

/**
 *
 *//*from   w  w  w.  j ava2 s  . c o m*/
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (Thread.interrupted()) {
        throw new PrinterException("Current thread interrupted.");
    }

    pageIndex += pageOffset;

    if (pageIndex < 0 || pageIndex >= jasperPrint.getPages().size()) {
        return Printable.NO_SUCH_PAGE;
    }

    try {
        JRGraphics2DExporter exporter = new JRGraphics2DExporter(jasperReportsContext);
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        SimpleGraphics2DExporterOutput output = new SimpleGraphics2DExporterOutput();
        output.setGraphics2D((Graphics2D) graphics);
        exporter.setExporterOutput(output);
        SimpleGraphics2DReportConfiguration configuration = new SimpleGraphics2DReportConfiguration();
        configuration.setPageIndex(pageIndex);
        exporter.setConfiguration(configuration);
        exporter.exportReport();
    } catch (JRException e) {
        if (log.isDebugEnabled()) {
            log.debug("Print failed.", e);
        }

        throw new PrinterException(e.getMessage()); //NOPMD
    }

    return Printable.PAGE_EXISTS;
}

From source file:org.apache.tez.runtime.task.TezTaskRunner.java

/**
 * @return false if a shutdown message was received during task execution
 * @throws TezException//from w ww .  j a  v  a  2s .c  o m
 * @throws IOException
 */
public boolean run() throws InterruptedException, IOException, TezException {
    waitingThread = Thread.currentThread();
    taskRunning.set(true);
    taskReporter.registerTask(task, this);
    TaskRunnerCallable callable = new TaskRunnerCallable();
    Throwable failureCause = null;
    taskFuture = executor.submit(callable);
    try {
        taskFuture.get();

        // Task could signal a fatal error and return control, or a failure while registering success.
        failureCause = firstException;

    } catch (InterruptedException e) {
        LOG.info("Interrupted while waiting for task to complete. Interrupting task");
        taskFuture.cancel(true);
        if (shutdownRequested.get()) {
            LOG.info("Shutdown requested... returning");
            return false;
        }
        if (firstException != null) {
            failureCause = firstException;
        } else {
            // Interrupted for some other reason.
            failureCause = e;
        }
    } catch (ExecutionException e) {
        // Exception thrown by the run() method itself.
        Throwable cause = e.getCause();
        if (cause instanceof FSError) {
            // Not immediately fatal, this is an error reported by Hadoop FileSystem
            failureCause = cause;
        } else if (cause instanceof Error) {
            LOG.error("Exception of type Error.", cause);
            sendFailure(cause, "Fatal Error cause TezChild exit.");
            throw new TezException("Fatal Error cause TezChild exit.", cause);
        } else {
            failureCause = cause;
        }
    } finally {
        // Clear the interrupted status of the blocking thread, in case it is set after the
        // InterruptedException was invoked.
        taskReporter.unregisterTask(task.getTaskAttemptID());
        Thread.interrupted();
    }

    if (failureCause != null) {
        if (failureCause instanceof FSError) {
            // Not immediately fatal, this is an error reported by Hadoop FileSystem
            LOG.info("Encountered an FSError while executing task: " + task.getTaskAttemptID(), failureCause);
            throw (FSError) failureCause;
        } else if (failureCause instanceof Error) {
            LOG.error("Exception of type Error.", failureCause);
            sendFailure(failureCause, "Fatal error cause TezChild exit.");
            throw new TezException("Fatal error cause TezChild exit.", failureCause);
        } else {
            if (failureCause instanceof IOException) {
                throw (IOException) failureCause;
            } else if (failureCause instanceof TezException) {
                throw (TezException) failureCause;
            } else if (failureCause instanceof InterruptedException) {
                throw (InterruptedException) failureCause;
            } else {
                throw new TezException(failureCause);
            }
        }
    }
    if (shutdownRequested.get()) {
        LOG.info("Shutdown requested... returning");
        return false;
    }
    return true;
}

From source file:com.cloudbees.jenkins.plugins.gogs.GogsSCMNavigator.java

private void add(TaskListener listener, SCMSourceObserver observer, GogsRepository repo)
        throws InterruptedException {
    String name = repo.getRepositoryName();
    if (!Pattern.compile(pattern).matcher(name).matches()) {
        listener.getLogger().format("Ignoring %s%n", name);
        return;/*from   w ww  .jav a 2s  . c  o  m*/
    }
    listener.getLogger().format("Proposing %s%n", name);
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }
    SCMSourceObserver.ProjectObserver projectObserver = observer.observe(name);
    GogsSCMSource scmSource = new GogsSCMSource(null, repoOwner, name);
    scmSource.setGogsConnector(getGogsConnector());
    scmSource.setCredentialsId(credentialsId);
    scmSource.setCheckoutCredentialsId(checkoutCredentialsId);
    scmSource.setAutoRegisterHook(isAutoRegisterHooks());
    scmSource.setGogsServerUrl(gogsServerUrl);
    scmSource.setSshPort(sshPort);
    projectObserver.addSource(scmSource);
    projectObserver.complete();
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.ConsumerZooKeeper.java

/**
 * ?consumer//w w  w  . ja va  2 s. co m
 * 
 * @param fetchManager
 */
public void unRegisterConsumer(final FetchManager fetchManager) {
    try {
        final FutureTask<ZKLoadRebalanceListener> futureTask = this.consumerLoadBalanceListeners
                .remove(fetchManager);
        if (futureTask != null) {
            final ZKLoadRebalanceListener listener = futureTask.get();
            if (listener != null) {
                // ??offsets
                listener.commitOffsets();
                this.zkClient.unsubscribeStateChanges(new ZKSessionExpireListenner(listener));
                final ZKGroupDirs dirs = this.metaZookeeper.new ZKGroupDirs(listener.consumerConfig.getGroup());
                this.zkClient.unsubscribeChildChanges(dirs.consumerRegistryDir, listener);
                log.info("unsubscribeChildChanges:" + dirs.consumerRegistryDir);
                // topic?
                for (final String topic : listener.topicSubcriberRegistry.keySet()) {
                    final String partitionPath = this.metaZookeeper.brokerTopicsPath + "/" + topic;
                    this.zkClient.unsubscribeChildChanges(partitionPath, listener);
                    log.info("unsubscribeChildChanges:" + partitionPath);
                }
                // ownership
                listener.releaseAllPartitionOwnership();
                // 
                ZkUtils.deletePath(this.zkClient,
                        listener.dirs.consumerRegistryDir + "/" + listener.consumerIdString);
            }
        }
    } catch (final InterruptedException e) {
        Thread.interrupted();
        log.error("Interrupted when unRegisterConsumer", e);
    } catch (final Exception e) {
        log.error("Error in unRegisterConsumer,maybe error when registerConsumer", e);
    }
}

From source file:com.alibaba.dragoon.common.protocol.transport.socket.SocketSessionImpl.java

public void init(DragoonSession session) {
    this.session = session;
    readThread = new Thread(getSessionName() + " session read") {

        public void run() {
            try {
                for (;;) {
                    DragoonMessage message = readMessage();
                    if (message != null) {
                        logReceiveMessage(message);
                        SocketSessionImpl.this.session.receiveMessage(message);
                    }/*  w  ww. j a va  2  s.  c  o m*/

                    if (state != DragoonSessionImpl.State.Established) {
                        break;
                    }

                    if (Thread.interrupted()) {
                        break;
                    }
                }
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }

            lock.lock();
            try {
                if (stopSignal != null) {
                    stopSignal.signalAll();
                }
            } finally {
                lock.unlock();
            }
        }
    };
    readThread.start();
}

From source file:com.github.rinde.opt.localsearch.Swaps.java

static <C, T> ImmutableList<ImmutableList<T>> opt2(ImmutableList<ImmutableList<T>> schedule,
        IntList startIndices, C context, RouteEvaluator<C, T> evaluator, boolean depthFirst,
        Optional<RandomGenerator> rng, Optional<? extends ProgressListener<T>> listener)
        throws InterruptedException {

    checkArgument(schedule.size() == startIndices.size());

    final Schedule<C, T> baseSchedule = Schedule.create(context, schedule, startIndices, evaluator);

    final Object2DoubleLinkedOpenHashMap<ImmutableList<T>> routeCostCache = new Object2DoubleLinkedOpenHashMap<>(
            CACHE_SIZE);/*from   w  w  w. ja  v a 2 s  .  co  m*/

    for (int i = 0; i < baseSchedule.routes.size(); i++) {
        routeCostCache.put(baseSchedule.routes.get(i), baseSchedule.objectiveValues.getDouble(i));
    }

    Schedule<C, T> bestSchedule = baseSchedule;
    boolean isImproving = true;
    while (isImproving) {
        isImproving = false;

        final Schedule<C, T> curBest = bestSchedule;
        Iterator<Swap<T>> it = swapIterator(curBest);
        if (depthFirst) {
            // randomize ordering of swaps
            final List<Swap<T>> swaps = newArrayList(it);
            Collections.shuffle(swaps, new RandomAdaptor(rng.get()));
            it = swaps.iterator();
        }

        while (it.hasNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
            final Swap<T> swapOperation = it.next();
            final Optional<Schedule<C, T>> newSchedule = swap(curBest, swapOperation,
                    bestSchedule.objectiveValue - curBest.objectiveValue, routeCostCache);

            if (newSchedule.isPresent()) {
                isImproving = true;
                bestSchedule = newSchedule.get();

                if (listener.isPresent()) {
                    listener.get().notify(bestSchedule.routes, bestSchedule.objectiveValue);
                }
                if (depthFirst) {
                    // first improving swap is chosen as new starting point (depth
                    // first).
                    break;
                }
            }
        }
    }
    return bestSchedule.routes;
}

From source file:eu.stratosphere.nephele.io.RuntimeInputGate.java

@Override
public InputChannelResult readRecord(T target) throws IOException, InterruptedException {

    if (this.channelToReadFrom == -1) {
        if (this.isClosed()) {
            return InputChannelResult.END_OF_STREAM;
        }//from  w  w w.ja v a  2  s . c  o  m

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

        this.channelToReadFrom = waitForAnyChannelToBecomeAvailable();
    }

    InputChannelResult result = this.getInputChannel(this.channelToReadFrom).readRecord(target);
    switch (result) {
    case INTERMEDIATE_RECORD_FROM_BUFFER: // full record and we can stay on the same channel
        return InputChannelResult.INTERMEDIATE_RECORD_FROM_BUFFER;

    case LAST_RECORD_FROM_BUFFER: // full record, but we must switch the channel afterwards
        this.channelToReadFrom = -1;
        return InputChannelResult.LAST_RECORD_FROM_BUFFER;

    case END_OF_SUPERSTEP:
        this.channelToReadFrom = -1;
        return InputChannelResult.END_OF_SUPERSTEP;

    case TASK_EVENT: // task event
        this.currentEvent = this.getInputChannel(this.channelToReadFrom).getCurrentEvent();
        this.channelToReadFrom = -1; // event always marks a unit as consumed
        return InputChannelResult.TASK_EVENT;

    case NONE: // internal event or an incomplete record that needs further chunks
        // the current unit is exhausted
        this.channelToReadFrom = -1;
        return InputChannelResult.NONE;

    case END_OF_STREAM: // channel is done
        this.channelToReadFrom = -1;
        return isClosed() ? InputChannelResult.END_OF_STREAM : InputChannelResult.NONE;

    default: // silence the compiler
        throw new RuntimeException();
    }
}

From source file:org.codice.alliance.video.stream.mpegts.rollover.CatalogRolloverAction.java

/**
 * @param sleep milliseconds to sleep//from  w ww  . j a  v a 2 s  .  c o  m
 * @return true if interrupted
 */
private boolean sleep(long sleep) {
    try {
        Thread.sleep(sleep);
    } catch (InterruptedException e) {
        LOGGER.warn("interrupted while waiting to attempt update request", e);
        Thread.interrupted();
        return true;
    }
    return false;
}