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:com.facebook.LinkBench.LinkBenchDriverInj.java

void sendrequests() throws IOException, InterruptedException, Throwable {

    if (!doRequest) {
        logger.info("Skipping request phase per the cmdline arg");
        return;//w  w w .  ja v  a2 s .c  o  m
    }

    // config info for requests
    nrequesters = ConfigUtil.getInt(props, Config.NUM_REQUESTERS);
    if (nrequesters == 0) {
        logger.info("NO REQUEST PHASE CONFIGURED. ");
        return;
    }
    List<LinkBenchRequestInj> requesters = new LinkedList<LinkBenchRequestInj>();

    RequestProgress progress = LinkBenchRequestInj.createProgress(logger, props);

    Random masterRandom = createMasterRNG(props, Config.REQUEST_RANDOM_SEED);
    requestrate = ConfigUtil.getLong(props, Config.REQUEST_RATE, 0L);
    maxTime = ConfigUtil.getLong(props, Config.MAX_TIME);

    genQueue = new ArrayBlockingQueue<Long>(1000000); // 10000 should be in Config really. TODO

    statsQueue = new ArrayBlockingQueue<StatMessage>(1000000); // 1000000 should be in Config. TODO

    // create GlobalStats thread

    GlobalStats gs = new GlobalStats(statsQueue, props, csvStreamFile);
    Thread t = new Thread(gs, "Global Stats Thread");
    t.start();

    // create requesters
    for (int i = 0; i < nrequesters; i++) {
        Stores stores = initStores();
        LinkBenchRequestInj l = new LinkBenchRequestInj(stores.linkStore, stores.nodeStore, props,
                csvStreamFile, progress, new Random(masterRandom.nextLong()), i, nrequesters, genQueue,
                statsQueue);
        requesters.add(l);
    }
    progress.startTimer();
    // run requesters
    concurrentExec(requesters, true, new Random(masterRandom.nextLong()));

    // stop Thread with global statistics
    t.interrupt();
    t.join();
    gs.printQuantileStats();

    long finishTime = System.currentTimeMillis();
    // Calculate duration accounting for warmup time
    long benchmarkTime = finishTime - progress.getBenchmarkStartTime();

    long requestsdone = 0;
    int abortedRequesters = 0;
    // wait for requesters
    for (LinkBenchRequestInj requester : requesters) {
        requestsdone += requester.getRequestsDone();
        if (requester.didAbort()) {
            abortedRequesters++;
        }
    }

    logger.info("REQUEST PHASE COMPLETED. " + requestsdone + " requests done in " + (benchmarkTime / 1000)
            + " seconds." + " Requests/second = " + (1000 * requestsdone) / benchmarkTime);
    if (abortedRequesters > 0) {
        logger.error(String.format(
                "Benchmark did not complete cleanly: %d/%d "
                        + "request threads aborted.  See error log entries for details.",
                abortedRequesters, nrequesters));
    }
}

From source file:org.codelibs.fess.servlet.Tomcat6ConfigServlet.java

@SuppressWarnings("deprecation")
private void cleanupAllThreads() {
    final Thread[] threads = getThreads();
    final ClassLoader cl = this.getClass().getClassLoader();
    try {//from  ww w  . java 2  s .  co  m
        cl.getResource(null);
    } catch (final Exception e) {
    }

    final List<String> jvmThreadGroupList = new ArrayList<String>();
    jvmThreadGroupList.add("system");
    jvmThreadGroupList.add("RMI Runtime");

    // Iterate over the set of threads
    for (final Thread thread : threads) {
        if (thread != null) {
            final ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl.equals(cl)) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }

                // Don't warn about JVM controlled threads
                final ThreadGroup tg = thread.getThreadGroup();
                if (tg != null && jvmThreadGroupList.contains(tg.getName())) {
                    continue;
                }

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Interrupting a thread [" + thread.getName() + "]...");
                }
                thread.interrupt();

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Stopping a thread [" + thread.getName() + "]...");
                }
                thread.stop();
            }
        }
    }

    Field threadLocalsField = null;
    Field inheritableThreadLocalsField = null;
    Field tableField = null;
    try {
        threadLocalsField = Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
        inheritableThreadLocalsField.setAccessible(true);
        // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
        // accessible
        final Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
        tableField = tlmClass.getDeclaredField("table");
        tableField.setAccessible(true);
    } catch (final Exception e) {
        // ignore
    }
    for (final Thread thread : threads) {
        if (thread != null) {

            Object threadLocalMap;
            try {
                // Clear the first map
                threadLocalMap = threadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
            try { // Clear the second map
                threadLocalMap = inheritableThreadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
        }
    }
}

From source file:org.rhq.enterprise.server.plugins.alertCli.CliSender.java

public SenderResult send(Alert alert) {
    SenderResult result = new SenderResult();
    BufferedReader reader = null;
    ScriptEngine engine = null;//w ww  .j a  va2s  .c  o  m
    Subject subjectWithSession = null;
    final SessionManager sessionManager = SessionManager.getInstance();

    try {
        final Config config = getConfig();

        // simulate the login by getting a session ID
        config.subject = sessionManager.put(config.subject, pluginComponent.getScriptTimeout() * 1000);
        subjectWithSession = config.subject;

        result.setSummary(createSummary(config, SUMMARY_TEMPLATE));

        ByteArrayOutputStream scriptOutputStream = new ByteArrayOutputStream();
        PrintWriter scriptOut = new PrintWriter(scriptOutputStream);

        engine = getScriptEngine(alert, scriptOut, config);

        InputStream packageBits = getPackageBits(config.packageId, config.repoId);

        reader = new BufferedReader(new InputStreamReader(packageBits));

        final BufferedReader rdr = reader;

        final ExceptionHolder exceptionHolder = new ExceptionHolder();

        final ScriptEngine e = engine;
        Thread scriptRunner = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    e.eval(rdr);
                } catch (ScriptException e) {
                    exceptionHolder.scriptException = e;
                } catch (Throwable e) {
                    exceptionHolder.throwable = e;
                }
            }
        }, "Script Runner for alert " + alert);
        scriptRunner.setDaemon(true);
        scriptRunner.start();

        if (pluginComponent.getScriptTimeout() <= 0) {
            scriptRunner.join();
        } else {
            scriptRunner.join(pluginComponent.getScriptTimeout() * 1000);
        }

        scriptRunner.interrupt();

        if (exceptionHolder.scriptException != null) {
            LOG.info("The script execution for CLI notification of alert [" + alert + "] failed.",
                    exceptionHolder.scriptException);

            //make things pretty for the UI
            ScriptEngineInitializer initializer = ScriptEngineFactory.getInitializer(ENGINE_NAME);
            String message = initializer.extractUserFriendlyErrorMessage(exceptionHolder.scriptException);
            int col = exceptionHolder.scriptException.getColumnNumber();
            int line = exceptionHolder.scriptException.getLineNumber();
            String scriptName = createSummary(config,
                    "script $packageName ($packageVersion) in repo $repoName");
            throw new ScriptException(message, scriptName, line, col);
        } else if (exceptionHolder.throwable != null) {
            LOG.info("The script execution for CLI notification of alert [" + alert + "] failed.",
                    exceptionHolder.throwable);

            throw exceptionHolder.throwable;
        }

        scriptOut.flush();
        String scriptOutput = scriptOutputStream.toString(Charset.defaultCharset().name());

        if (scriptOutput.length() == 0) {
            scriptOutput = "Script generated no output.";
        }

        if (scriptOutput.length() > remainingResultSize(result)) {
            scriptOutput = scriptOutput.substring(0, remainingResultSize(result));
        }

        result.addSuccessMessage(scriptOutput);

        return result;
    } catch (IllegalArgumentException e) {
        return SenderResult.getSimpleFailure(e.getMessage()); //well, let's just hope the message doesn't exceed 4k.
    } catch (Throwable e) {
        result.addFailureMessage(ThrowableUtil.getAllMessages(e, true, remainingResultSize(result)));
        return result;
    } finally {
        if (subjectWithSession != null) {
            sessionManager.invalidate(subjectWithSession.getSessionId());
        }
        if (engine != null) {
            returnEngine(engine);
        }

        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                LOG.error("Failed to close the script reader.", e);
            }
        }
    }
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testSafeSleep() throws InterruptedException {
    final AtomicBoolean value = new AtomicBoolean(false);
    final Thread thread = new Thread(() -> {
        // Value will not be set if safe sleep throws or is not interrupted.
        ApacheHttpSink.safeSleep(500);/*from  w ww .  j a  v a  2 s .  c  o m*/
        value.set(true);
    });

    thread.start();
    Thread.sleep(100);
    thread.interrupt();
    thread.join(600);

    Assert.assertFalse(thread.isAlive());
    Assert.assertTrue(value.get());
}

From source file:hudson.model.AbstractProjectTest.java

/**
 * Unless the concurrent build option is enabled, polling and build should
 * be mutually exclusive to avoid allocating unnecessary workspaces.
 *//*from w w w  .  jav  a2s.c om*/
@Test
@Issue("JENKINS-4202")
public void pollingAndBuildExclusion() throws Exception {
    final OneShotEvent sync = new OneShotEvent();

    final FreeStyleProject p = j.createFreeStyleProject();
    FreeStyleBuild b1 = j.buildAndAssertSuccess(p);

    p.setScm(new NullSCM() {
        @Override
        public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace,
                TaskListener listener) {
            try {
                sync.block();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return true;
        }

        /**
         * Don't write 'this', so that subtypes can be implemented as
         * anonymous class.
         */
        private Object writeReplace() {
            return new Object();
        }

        @Override
        public boolean requiresWorkspaceForPolling() {
            return true;
        }

        @Override
        public SCMDescriptor<?> getDescriptor() {
            return new SCMDescriptor<SCM>(null) {
            };
        }
    });
    Thread t = new Thread() {
        @Override
        public void run() {
            p.pollSCMChanges(StreamTaskListener.fromStdout());
        }
    };
    try {
        t.start();
        Future<FreeStyleBuild> f = p.scheduleBuild2(0);

        // add a bit of delay to make sure that the blockage is happening
        Thread.sleep(3000);

        // release the polling
        sync.signal();

        FreeStyleBuild b2 = j.assertBuildStatusSuccess(f);

        // they should have used the same workspace.
        assertEquals(b1.getWorkspace(), b2.getWorkspace());
    } finally {
        t.interrupt();
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * {@inheritDoc}/*from  w  w  w.  j  a  v a 2s.c om*/
 */
public void disconnect() {
    if (jobThread != null) {
        Thread t = jobThread;
        jobThread = null;
        t.interrupt();
    }
    if (context != null) {
        try {
            context.close();
        } catch (NamingException e) {
            // ignore
        }
        context = null;
    }
    isConnected = false;
}

From source file:com.linkedin.helix.TestHelper.java

public static <T> Map<String, T> startThreadsConcurrently(final int nrThreads, final Callable<T> method,
        final long timeout) {
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishCounter = new CountDownLatch(nrThreads);
    final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>();
    final List<Thread> threadList = new ArrayList<Thread>();

    for (int i = 0; i < nrThreads; i++) {
        Thread thread = new Thread() {
            @Override/* w  ww .j  av a  2  s  .  co  m*/
            public void run() {
                try {
                    boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS);
                    if (isTimeout) {
                        LOG.error("Timeout while waiting for start latch");
                    }
                } catch (InterruptedException ex) {
                    LOG.error("Interrupted while waiting for start latch");
                }

                try {
                    T result = method.call();
                    if (result != null) {
                        resultsMap.put("thread_" + this.getId(), result);
                    }
                    LOG.debug("result=" + result);
                } catch (Exception e) {
                    LOG.error("Exeption in executing " + method.getClass().getName(), e);
                }

                finishCounter.countDown();
            }
        };
        threadList.add(thread);
        thread.start();
    }
    startLatch.countDown();

    // wait for all thread to complete
    try {
        boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS);
        if (isTimeout) {
            LOG.error("Timeout while waiting for finish latch. Interrupt all threads");
            for (Thread thread : threadList) {
                thread.interrupt();
            }
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for finish latch", e);
    }

    return resultsMap;
}

From source file:com.linkedin.helix.TestHelper.java

public static <T> Map<String, T> startThreadsConcurrently(final List<Callable<T>> methods, final long timeout) {
    final int nrThreads = methods.size();
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishCounter = new CountDownLatch(nrThreads);
    final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>();
    final List<Thread> threadList = new ArrayList<Thread>();

    for (int i = 0; i < nrThreads; i++) {
        final Callable<T> method = methods.get(i);

        Thread thread = new Thread() {
            @Override/*  w  w  w .j  av  a  2  s  .  c  o  m*/
            public void run() {
                try {
                    boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS);
                    if (isTimeout) {
                        LOG.error("Timeout while waiting for start latch");
                    }
                } catch (InterruptedException ex) {
                    LOG.error("Interrupted while waiting for start latch");
                }

                try {
                    T result = method.call();
                    if (result != null) {
                        resultsMap.put("thread_" + this.getId(), result);
                    }
                    LOG.debug("result=" + result);
                } catch (Exception e) {
                    LOG.error("Exeption in executing " + method.getClass().getName(), e);
                }

                finishCounter.countDown();
            }
        };
        threadList.add(thread);
        thread.start();
    }
    startLatch.countDown();

    // wait for all thread to complete
    try {
        boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS);
        if (isTimeout) {
            LOG.error("Timeout while waiting for finish latch. Interrupt all threads");
            for (Thread thread : threadList) {
                thread.interrupt();
            }
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for finish latch", e);
    }

    return resultsMap;
}

From source file:org.kurento.test.base.BrowserTest.java

public void getFrames(final File inputFile, final File tmpFolder) {
    Thread t = new Thread() {
        @Override//from   w  w  w . j a  v  a2  s .c om
        public void run() {
            String[] command = { "ffmpeg", "-i", inputFile.getAbsolutePath(),
                    tmpFolder.toString() + File.separator + inputFile.getName() + "-%03d" + PNG };
            log.debug("Running command to get frames: {}", Arrays.toString(command));
            Shell.runAndWait(command);
        }
    };
    t.start();
    waitMilliSeconds(500);
    t.interrupt();
}

From source file:org.apache.hadoop.hbase.tool.Canary.java

@Override
public int run(String[] args) throws Exception {
    int index = -1;

    // Process command line args
    for (int i = 0; i < args.length; i++) {
        String cmd = args[i];//from   w ww . jav a 2s.c o m

        if (cmd.startsWith("-")) {
            if (index >= 0) {
                // command line args must be in the form: [opts] [table 1 [table 2 ...]]
                System.err.println("Invalid command line options");
                printUsageAndExit();
            }

            if (cmd.equals("-help")) {
                // user asked for help, print the help and quit.
                printUsageAndExit();
            } else if (cmd.equals("-daemon") && interval == 0) {
                // user asked for daemon mode, set a default interval between checks
                interval = DEFAULT_INTERVAL;
            } else if (cmd.equals("-interval")) {
                // user has specified an interval for canary breaths (-interval N)
                i++;

                if (i == args.length) {
                    System.err.println("-interval needs a numeric value argument.");
                    printUsageAndExit();
                }

                try {
                    interval = Long.parseLong(args[i]) * 1000;
                } catch (NumberFormatException e) {
                    System.err.println("-interval needs a numeric value argument.");
                    printUsageAndExit();
                }
            } else if (cmd.equals("-regionserver")) {
                this.regionServerMode = true;
            } else if (cmd.equals("-e")) {
                this.useRegExp = true;
            } else if (cmd.equals("-t")) {
                i++;

                if (i == args.length) {
                    System.err.println("-t needs a numeric value argument.");
                    printUsageAndExit();
                }

                try {
                    this.timeout = Long.parseLong(args[i]);
                } catch (NumberFormatException e) {
                    System.err.println("-t needs a numeric value argument.");
                    printUsageAndExit();
                }

            } else if (cmd.equals("-f")) {
                i++;

                if (i == args.length) {
                    System.err.println("-f needs a boolean value argument (true|false).");
                    printUsageAndExit();
                }

                this.failOnError = Boolean.parseBoolean(args[i]);
            } else {
                // no options match
                System.err.println(cmd + " options is invalid.");
                printUsageAndExit();
            }
        } else if (index < 0) {
            // keep track of first table name specified by the user
            index = i;
        }
    }

    // start to prepare the stuffs
    Monitor monitor = null;
    Thread monitorThread = null;
    long startTime = 0;
    long currentTimeLength = 0;

    do {
        // do monitor !!
        monitor = this.newMonitor(index, args);
        monitorThread = new Thread(monitor);
        startTime = System.currentTimeMillis();
        monitorThread.start();
        while (!monitor.isDone()) {
            // wait for 1 sec
            Thread.sleep(1000);
            // exit if any error occurs
            if (this.failOnError && monitor.hasError()) {
                monitorThread.interrupt();
                if (monitor.initialized) {
                    System.exit(monitor.errorCode);
                } else {
                    System.exit(INIT_ERROR_EXIT_CODE);
                }
            }
            currentTimeLength = System.currentTimeMillis() - startTime;
            if (currentTimeLength > this.timeout) {
                LOG.error("The monitor is running too long (" + currentTimeLength + ") after timeout limit:"
                        + this.timeout + " will be killed itself !!");
                if (monitor.initialized) {
                    System.exit(TIMEOUT_ERROR_EXIT_CODE);
                } else {
                    System.exit(INIT_ERROR_EXIT_CODE);
                }
                break;
            }
        }

        if (this.failOnError && monitor.hasError()) {
            monitorThread.interrupt();
            System.exit(monitor.errorCode);
        }

        Thread.sleep(interval);
    } while (interval > 0);

    return (monitor.errorCode);
}