Example usage for java.lang Thread isInterrupted

List of usage examples for java.lang Thread isInterrupted

Introduction

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

Prototype

public boolean isInterrupted() 

Source Link

Document

Tests whether this thread has been interrupted.

Usage

From source file:org.hyperic.lather.server.LatherServlet.java

private void doServiceCall(HttpServletRequest req, HttpServletResponse resp, String methName, LatherValue args,
        LatherXCoder xCoder, LatherContext ctx) throws IOException {

    final LatherDispatcher latherDispatcher = Bootstrap.getBean(LatherDispatcher.class);
    final ServiceCaller caller = new ServiceCaller(resp, xCoder, ctx, methName, args, latherDispatcher);
    final Thread currentThread = Thread.currentThread();
    final String threadName = currentThread.getName();

    try {/* w  w w .  j  av  a 2s  . c o  m*/
        currentThread.setName(methName + "-" + ids.getAndIncrement());
        LatherThreadMonitor.get().register(caller);
        caller.run();
        if (currentThread.isInterrupted()) {
            throw new InterruptedException();
        }
    } catch (InterruptedException exc) {
        log.warn("Interrupted while trying to execute lather method=" + methName + " from ip="
                + ctx.getCallerIP());
    } finally {
        caller.markFinished();
        currentThread.setName(threadName);
    }
}

From source file:org.openspaces.maven.plugin.RunStandalonePUMojo.java

/**
 * executes the mojo./*from w w  w.j  a va 2s . co m*/
 */
public void executeMojo() throws MojoExecutionException, MojoFailureException {

    // Remove white spaces from ClassLoader's URLs
    ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
    try {
        Utils.changeClassLoaderToSupportWhiteSpacesRepository(currentCL);
    } catch (Exception e) {
        PluginLog.getLog().info("Unable to update ClassLoader. Proceeding with processing unit invocation.", e);
    }

    Utils.handleSecurity();
    try {
        ClassUtils.forName("com.gigaspaces.logger.GSLogConfigLoader", null).getMethod("getLoader", new Class[0])
                .invoke(null, new Object[0]);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to configure logging", e);
    }

    // get a list of project to execute in the order set by the reactor
    List<MavenProject> projects = Utils.getProjectsToExecute(reactorProjects, module);

    for (MavenProject proj : projects) {
        executePU(proj);
    }

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                for (int i = (containers.size() - 1); i >= 0; --i) {
                    containers.get(i).interrupt();
                }
            } finally {
                mainThread.interrupt();
            }
        }
    });
    while (!mainThread.isInterrupted()) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            // do nothing, simply exit
        }
    }

}

From source file:org.openspaces.maven.plugin.RunPUMojo.java

/**
 * Executed the Mojo.//from ww  w .  j a v a 2  s  .  c  o m
 */
public void executeMojo() throws MojoExecutionException, MojoFailureException {
    // Remove white spaces from ClassLoader's URLs
    ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
    try {
        Utils.changeClassLoaderToSupportWhiteSpacesRepository(currentCL);
    } catch (Exception e) {
        PluginLog.getLog().info("Unable to update ClassLoader. Proceeding with processing unit invocation.", e);
    }

    Utils.handleSecurity();
    try {
        ClassUtils.forName("com.gigaspaces.logger.GSLogConfigLoader", null).getMethod("getLoader", new Class[0])
                .invoke(null, new Object[0]);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to configure logging", e);
    }

    // get a list of project to execute in the order set by the reactor
    List projects = Utils.getProjectsToExecute(reactorProjects, module);

    for (Iterator projIt = projects.iterator(); projIt.hasNext();) {
        MavenProject proj = (MavenProject) projIt.next();
        executePU(proj);
    }

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                for (int i = (containers.size() - 1); i >= 0; --i) {
                    ((Thread) containers.get(i)).interrupt();
                }
            } finally {
                mainThread.interrupt();
            }
        }
    });

    while (!mainThread.isInterrupted()) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            // do nothing, simply exit
        }
    }
}

From source file:net.dv8tion.jda.player.source.RemoteSource.java

@Override
public File asFile(String path, boolean deleteIfExists)
        throws FileAlreadyExistsException, FileNotFoundException {
    if (path == null || path.isEmpty())
        throw new NullPointerException("Provided path was null or empty!");

    File file = new File(path);
    if (file.isDirectory())
        throw new IllegalArgumentException("The provided path is a directory, not a file!");
    if (file.exists()) {
        if (!deleteIfExists) {
            throw new FileAlreadyExistsException("The provided path already has an existing file "
                    + " and the `deleteIfExists` boolean was set to false.");
        } else {//  w  w w .j  a  v  a2s  .com
            if (!file.delete())
                throw new UnsupportedOperationException("Cannot delete the file. Is it in use?");
        }
    }

    Thread currentThread = Thread.currentThread();
    FileOutputStream fos = new FileOutputStream(file);
    InputStream input = asStream();

    //Writes the bytes of the downloaded audio into the file.
    //Has detection to detect if the current thread has been interrupted to respect calls to
    // Thread#interrupt() when an instance of RemoteSource is in an async thread.
    //TODO: consider replacing with a Future.
    try {
        byte[] buffer = new byte[1024];
        int amountRead = -1;
        int i = 0;
        while (!currentThread.isInterrupted() && ((amountRead = input.read(buffer)) > -1)) {
            fos.write(buffer, 0, amountRead);
        }
        fos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file;
}

From source file:tap.formatter.JSONFormat.java

@Override
public void writeResult(TableIterator result, OutputStream output, TAPExecutionReport execReport, Thread thread)
        throws TAPException, IOException, InterruptedException {
    try {/* ww  w .  ja v  a  2 s .c om*/

        // Prepare the output stream for JSON:
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
        JSONWriter out = new JSONWriter(writer);

        // {
        out.object();

        // "metadata": [...]
        out.key("metadata");

        // Write metadata part:
        DBColumn[] columns = writeMetadata(result, out, execReport, thread);

        writer.flush();

        if (thread.isInterrupted())
            throw new InterruptedException();

        // "data": [...]
        out.key("data");

        // Write the data part:
        writeData(result, columns, out, execReport, thread);

        // }
        out.endObject();
        writer.flush();

    } catch (JSONException je) {
        throw new TAPException(je.getMessage(), je);
    }
}

From source file:LinkedTransferQueue.java

/**
 * Spins/blocks until node s is fulfilled or caller gives up,
 * depending on wait mode.//from  www.j av a  2  s.  com
 *
 * @param pred the predecessor of waiting node
 * @param s the waiting node
 * @param e the comparison value for checking match
 * @param mode mode
 * @param nanos timeout value
 * @return matched item, or s if cancelled
 */
private Object awaitFulfill(QNode pred, QNode s, Object e, int mode, long nanos) {
    if (mode == NOWAIT) {
        return null;
    }

    long lastTime = mode == TIMEOUT ? System.nanoTime() : 0;
    Thread w = Thread.currentThread();
    int spins = -1; // set to desired spin count below
    for (;;) {
        if (w.isInterrupted()) {
            s.compareAndSet(e, s);
        }
        Object x = s.get();
        if (x != e) { // Node was matched or cancelled
            advanceHead(pred, s); // unlink if head
            if (x == s) { // was cancelled
                clean(pred, s);
                return null;
            } else if (x != null) {
                s.set(s); // avoid garbage retention
                return x;
            } else {
                return e;
            }
        }
        if (mode == TIMEOUT) {
            long now = System.nanoTime();
            nanos -= now - lastTime;
            lastTime = now;
            if (nanos <= 0) {
                s.compareAndSet(e, s); // try to cancel
                continue;
            }
        }
        if (spins < 0) {
            QNode h = this.head.get(); // only spin if at head
            spins = h != null && h.next == s ? (mode == TIMEOUT ? maxTimedSpins : maxUntimedSpins) : 0;
        }
        if (spins > 0) {
            --spins;
        } else if (s.waiter == null) {
            s.waiter = w;
        } else if (mode != TIMEOUT) {
            //                LockSupport.park(this);
            LockSupport.park(); // allows run on java5
            s.waiter = null;
            spins = -1;
        } else if (nanos > spinForTimeoutThreshold) {
            //                LockSupport.parkNanos(this, nanos);
            LockSupport.parkNanos(nanos);
            s.waiter = null;
            spins = -1;
        }
    }
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadDetails(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String threadLocation = "";
            try {
                StackTraceElement ste = thread.getStackTrace()[0];
                StackTraceElement ste2 = thread.getStackTrace()[1];
                threadLocation = ste.getClassName() + "." + ste.getMethodName() + "()," + ste.getFileName()
                        + ":" + ste.getLineNumber() + "," + ste2.getClassName() + "." + ste2.getMethodName()
                        + "()," + ste2.getFileName() + ":" + ste2.getLineNumber();
            } catch (Exception e) {
                threadLocation = "?,?,?,?";
            }//from w  w  w .j  av a 2s  . co m
            pw.print(thread.getThreadGroup().getName() + "," + thread.getId() + "," + thread.getName() + ","
                    + thread.getPriority() + "," + thread.getState().name() + ","
                    + (thread.isAlive() ? "" : "notalive") + "," + (thread.isDaemon() ? "daemon" : "") + ","
                    + (thread.isInterrupted() ? "interrupted" : "") + "," + threadLocation + "\n");
        }
    }
}

From source file:LinkedTransferQueue.java

/**
 * Spins/yields/blocks until node s is matched or caller gives up.
 *
 * @param s the waiting node//  ww w.  j  a v  a 2 s .  c o  m
 * @param pred the predecessor of s, or s itself if it has no
 * predecessor, or null if unknown (the null case does not occur
 * in any current calls but may in possible future extensions)
 * @param e the comparison value for checking match
 * @param timed if true, wait only until timeout elapses
 * @param nanos timeout in nanosecs, used only if timed is true
 * @return matched item, or e if unmatched on interrupt or timeout
 */
private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) {
    long lastTime = timed ? System.nanoTime() : 0L;
    Thread w = Thread.currentThread();
    int spins = -1; // initialized after first item and cancel checks
    ThreadLocalRandom randomYields = null; // bound if needed

    for (;;) {
        Object item = s.item;
        if (item != e) { // matched
            assert item != s;
            s.forgetContents(); // avoid garbage
            return this.<E>cast(item);
        }
        if ((w.isInterrupted() || (timed && nanos <= 0)) && s.casItem(e, s)) { // cancel
            unsplice(pred, s);
            return e;
        }

        if (spins < 0) { // establish spins at/near front
            if ((spins = spinsFor(pred, s.isData)) > 0)
                randomYields = ThreadLocalRandom.current();
        } else if (spins > 0) { // spin
            --spins;
            if (randomYields.nextInt(CHAINED_SPINS) == 0)
                Thread.yield(); // occasionally yield
        } else if (s.waiter == null) {
            s.waiter = w; // request unpark then recheck
        } else if (timed) {
            long now = System.nanoTime();
            if ((nanos -= now - lastTime) > 0)
                LockSupport.parkNanos(this, nanos);
            lastTime = now;
        } else {
            LockSupport.park(this);
        }
    }
}

From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java

/**
 * Interrupts threads that might be waiting for tasks (as indicated by not
 * being locked) so they can check for termination or configuration changes.
 * Ignores SecurityExceptions (in which case some threads may remain
 * uninterrupted)./*from   www.  j  a v  a2s.co m*/
 * 
 * @param onlyOne
 *            If true, interrupt at most one worker. This is called only
 *            from tryTerminate when termination is otherwise enabled but
 *            there are still other workers. In this case, at most one
 *            waiting worker is interrupted to propagate shutdown signals in
 *            case all threads are currently waiting. Interrupting any
 *            arbitrary thread ensures that newly arriving workers since
 *            shutdown began will also eventually exit. To guarantee
 *            eventual termination, it suffices to always interrupt only one
 *            idle worker, but shutdown() interrupts all idle workers so
 *            that redundant workers exit promptly, not waiting for a
 *            straggler task to finish.
 */
private void interruptIdleWorkers(boolean onlyOne) {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        for (Worker w : workers) {
            Thread t = w.thread;
            if (!t.isInterrupted() && w.tryLock()) {
                try {
                    t.interrupt();
                } catch (SecurityException ignore) {
                } finally {
                    w.unlock();
                }
            }
            if (onlyOne)
                break;
        }
    } finally {
        mainLock.unlock();
    }
}

From source file:org.apache.oozie.coord.CoordELFunctions.java

private static String coord_futureRange_sync(int startOffset, int endOffset, int instance) throws Exception {
    final XLog LOG = XLog.getLog(CoordELFunctions.class);
    final Thread currentThread = Thread.currentThread();
    ELEvaluator eval = ELEvaluator.getCurrent();
    String retVal = "";
    int datasetFrequency = (int) getDSFrequency();// in minutes
    TimeUnit dsTimeUnit = getDSTimeUnit();
    int[] instCount = new int[1];
    Calendar nominalInstanceCal = getCurrentInstance(getActionCreationtime(), instCount);
    StringBuilder resolvedInstances = new StringBuilder();
    StringBuilder resolvedURIPaths = new StringBuilder();
    if (nominalInstanceCal != null) {
        Calendar initInstance = getInitialInstanceCal();
        nominalInstanceCal = (Calendar) initInstance.clone();
        nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), instCount[0] * datasetFrequency);

        SyncCoordDataset ds = (SyncCoordDataset) eval.getVariable(DATASET);
        if (ds == null) {
            throw new RuntimeException("Associated Dataset should be defined with key " + DATASET);
        }//from www . jav a  2s  .c  o  m
        String uriTemplate = ds.getUriTemplate();
        Configuration conf = (Configuration) eval.getVariable(CONFIGURATION);
        if (conf == null) {
            throw new RuntimeException("Associated Configuration should be defined with key " + CONFIGURATION);
        }
        int available = 0, checkedInstance = 0;
        boolean resolved = false;
        String user = ParamChecker.notEmpty((String) eval.getVariable(OozieClient.USER_NAME),
                OozieClient.USER_NAME);
        String doneFlag = ds.getDoneFlag();
        URIHandlerService uriService = Services.get().get(URIHandlerService.class);
        URIHandler uriHandler = null;
        Context uriContext = null;
        try {
            while (instance >= checkedInstance && !currentThread.isInterrupted()) {
                ELEvaluator uriEval = getUriEvaluator(nominalInstanceCal);
                String uriPath = uriEval.evaluate(uriTemplate, String.class);
                if (uriHandler == null) {
                    URI uri = new URI(uriPath);
                    uriHandler = uriService.getURIHandler(uri);
                    uriContext = uriHandler.getContext(uri, conf, user, true);
                }
                String uriWithDoneFlag = uriHandler.getURIWithDoneFlag(uriPath, doneFlag);
                if (uriHandler.exists(new URI(uriWithDoneFlag), uriContext)) {
                    if (available == endOffset) {
                        LOG.debug("Matched future(" + available + "): " + uriWithDoneFlag);
                        resolved = true;
                        resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal));
                        resolvedURIPaths.append(uriPath);
                        retVal = resolvedInstances.toString();
                        eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString());
                        break;
                    } else if (available >= startOffset) {
                        LOG.debug("Matched future(" + available + "): " + uriWithDoneFlag);
                        resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal))
                                .append(INSTANCE_SEPARATOR);
                        resolvedURIPaths.append(uriPath).append(INSTANCE_SEPARATOR);

                    }
                    available++;
                }
                // nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), datasetFrequency);
                nominalInstanceCal = (Calendar) initInstance.clone();
                instCount[0]++;
                nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), instCount[0] * datasetFrequency);
                checkedInstance++;
                // DateUtils.moveToEnd(nominalInstanceCal, getDSEndOfFlag());
            }
            if (!StringUtils.isEmpty(resolvedURIPaths.toString())
                    && eval.getVariable(CoordELConstants.RESOLVED_PATH) == null) {
                eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString());
            }

        } finally {
            if (uriContext != null) {
                uriContext.destroy();
            }
        }
        if (!resolved) {
            // return unchanged future function with variable 'is_resolved'
            // to 'false'
            eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.FALSE);
            if (startOffset == endOffset) {
                retVal = "${coord:future(" + startOffset + ", " + instance + ")}";
            } else {
                retVal = "${coord:futureRange(" + startOffset + ", " + endOffset + ", " + instance + ")}";
            }
        } else {
            eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.TRUE);
        }
    } else {// No feasible nominal time
        eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.TRUE);
        retVal = "";
    }
    return retVal;
}