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:org.neo4j.server.web.LimitRequestTimeFilter.java

private TimerTask createTimer(int timeLimit) {
    final Thread current = Thread.currentThread();
    TimerTask timerTask = new TimerTask() {
        @Override/*from  ww  w.  j a va  2s .  co m*/
        public void run() {
            LOG.warn("request canceld");
            current.interrupt();
        }
    };
    timer.schedule(timerTask, timeLimit);
    return timerTask;
}

From source file:ubic.gemma.web.controller.common.auditAndSecurity.SignupControllerTest.java

@SuppressWarnings("Duplicates") // Not in this project
@Test/*ww w  .  j  a va 2  s.com*/
public void testSignup() throws Exception {
    int numThreads = 10; // too high and we run out of connections, which is not what we're testing.
    final int numsignupsperthread = 20;
    final Random random = new Random();
    final AtomicInteger c = new AtomicInteger(0);
    final AtomicBoolean failed = new AtomicBoolean(false);
    Collection<Thread> threads = new HashSet<>();
    for (int i = 0; i < numThreads; i++) {

        Thread k = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int j = 0; j < numsignupsperthread; j++) {
                        MockHttpServletRequest req;
                        Thread.sleep(random.nextInt(50));
                        req = new MockHttpServletRequest("POST", "/signup.html");
                        String uname = RandomStringUtils.randomAlphabetic(10);
                        // log.info( "Signingup: " + uname + " (" + c.get() + ")" );

                        String password = RandomStringUtils.randomAlphabetic(40);
                        req.addParameter("password", password);

                        req.addParameter("passwordConfirm", password);
                        req.addParameter("username", uname);
                        String email = "foo@" + RandomStringUtils.randomAlphabetic(10) + ".edu";
                        req.addParameter("email", email);

                        req.addParameter("emailConfirm", email);
                        suc.signup(req, new MockHttpServletResponse());

                        /*
                         * Extra torture.
                         */
                        ExpressionExperiment ee = ExpressionExperiment.Factory.newInstance();
                        ee.setDescription("From test");
                        ee.setName(RandomStringUtils.randomAlphabetic(20));
                        ee.setShortName(RandomStringUtils.randomAlphabetic(20));
                        // log.info( "Making experiment" + ee.getName() );
                        expressionExperimentService.create(ee);

                        c.incrementAndGet();

                    }
                } catch (Exception e) {
                    failed.set(true);
                    log.error("!!!!!!!!!!!!!!!!!!!!!! FAILED: " + e.getMessage());
                    log.debug(e, e);
                    throw new RuntimeException(e);
                }
                log.debug("Thread done.");
            }
        });
        threads.add(k);

        k.start();
    }

    int waits = 0;
    int maxWaits = 20;
    int expectedEventCount = numThreads * numsignupsperthread;
    while (c.get() < expectedEventCount && !failed.get()) {
        Thread.sleep(3000);
        log.info("Waiting ... C=" + +c.get());
        if (++waits > maxWaits) {
            for (Thread t : threads) {
                if (t.isAlive())
                    t.interrupt();
            }
            fail("Multithreaded failure: timed out.");
        }
    }

    log.debug(" &&&&& DONE &&&&&");

    for (Thread thread : threads) {
        if (thread.isAlive())
            thread.interrupt();
    }

    if (failed.get() || c.get() != expectedEventCount) {
        fail("Multithreaded loading failure: check logs for failure to recover from deadlock?");
    } else {
        log.info("TORTURE TEST PASSED!");
    }
}

From source file:org.onecmdb.core.internal.job.JobSchedulare.java

public void cancel(ICi trigger) {
    // Interuppt job.
    log.info("Interuppt job " + trigger.getAlias());
    Thread t = eventThreads.get(trigger.getAlias());
    if (t != null) {
        t.interrupt();
        eventThreads.remove(trigger.getAlias());
    } else {/*from w w  w .  ja v a  2s.co m*/
        try {
            sched.interrupt(trigger.getAlias(), null);

            log.info("Delete job " + trigger.getAlias());
            sched.deleteJob(trigger.getAlias(), null);

        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.mule.security.oauth.FetchAccessTokenTestCase.java

/**
 * When the event is restored from a persistent object store everything works
 * perfectly. However, when using in memory object stores the reference to the
 * event's owner thread is kept and throws exception when its properties are
 * modified. For this reason, the event's access control needs to be reset when
 * restored. This tests verifies that this is so
 *//*from w  w  w . j  a  va 2 s  .  c o  m*/
@Test
public void inMemoryObjectStore() throws Exception {
    this.objectStore.store("whatever-authorization-event", event);

    Thread t = new Thread(this);
    t.start();

    if (latch.await(1, TimeUnit.SECONDS)) {
        if (this.exception != null) {
            throw this.exception;
        }
    } else {
        t.interrupt();
        fail("timeout");
    }
}

From source file:com.iwedia.adapters.FragmentTabAdapter.java

/**
 * Stops background thread./* w  ww  .  ja va 2 s.  c  o m*/
 */
private synchronized void stopThread() {
    if (mTimerThread != null) {
        Thread moribund = mTimerThread;
        mTimerThread = null;
        moribund.interrupt();
    }
}

From source file:ubc.pavlab.aspiredb.server.controller.SignupControllerTest.java

@Test
public void testSignup() throws Exception {

    int numThreads = 10; // too high and we run out of connections, which is not what we're testing.
    final int numsignupsperthread = 10;
    final Random random = new Random();
    final AtomicInteger c = new AtomicInteger(0);
    final AtomicBoolean failed = new AtomicBoolean(false);
    Collection<Thread> threads = new HashSet<Thread>();
    final Collection<String> unames = Collections.synchronizedList(new ArrayList<String>());

    for (int i = 0; i < numThreads; i++) {

        Thread k = new Thread(new Runnable() {
            @Override/*from w w w. j  av  a  2s  .  c  o  m*/
            public void run() {
                try {
                    for (int j = 0; j < numsignupsperthread; j++) {
                        MockHttpServletRequest req = null;
                        Thread.sleep(random.nextInt(50));
                        req = new MockHttpServletRequest("POST", "/signup.html");
                        final String uname = RandomStringUtils.randomAlphabetic(10);

                        synchronized (unames) {
                            unames.add(uname);
                        }

                        // log.info( "Signingup: " + uname + " (" + c.get() + ")" );

                        String password = RandomStringUtils.randomAlphabetic(40);
                        req.addParameter("password", password);

                        req.addParameter("passwordConfirm", password);
                        req.addParameter("username", uname);
                        String email = "foo@" + RandomStringUtils.randomAlphabetic(10) + ".edu";
                        req.addParameter("email", email);
                        suc.signup(req, new MockHttpServletResponse());

                        // Cleanup
                        // userService.delete( userService.findByUserName( uname ) );

                        c.incrementAndGet();

                    }
                } catch (Exception e) {
                    failed.set(true);
                    log.error("!!!!!!!!!!!!!!!!!!!!!! FAILED: " + e.getMessage());
                    log.debug(e, e);
                    throw new RuntimeException(e);
                }
                log.debug("Thread done.");
            }
        });
        threads.add(k);

        k.start();
    }

    int waits = 0;
    int maxWaits = 30;
    int expectedEventCount = numThreads * numsignupsperthread;
    while (c.get() < expectedEventCount && !failed.get()) {
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Waiting ... C=" + +c.get());
        if (++waits > maxWaits) {
            for (Thread t : threads) {
                if (t.isAlive())
                    t.interrupt();
            }
            fail("Multithreaded failure: timed out.");
        }
    }

    // cleanup
    for (String uname : unames) {
        userService.delete(userService.findByUserName(uname));
    }

    log.debug(" &&&&& DONE &&&&&");

    for (Thread thread : threads) {
        if (thread.isAlive())
            thread.interrupt();
    }

    if (failed.get() || c.get() != expectedEventCount) {
        fail("Multithreaded loading failure: check logs for failure to recover from deadlock?");
    } else {
        log.info("TORTURE TEST PASSED!");
    }

}

From source file:org.apache.hadoop.hive.ql.DriverContext.java

/**
 * Cleans up remaining tasks in case of failure
 *//*  w  w  w  .j  ava  2  s . c om*/
public synchronized void shutdown() {
    LOG.debug("Shutting down query " + ctx.getCmd());
    shutdown = true;
    for (TaskRunner runner : running) {
        if (runner.isRunning()) {
            Task<?> task = runner.getTask();
            LOG.warn("Shutting down task : " + task);
            try {
                task.shutdown();
            } catch (Exception e) {
                console.printError("Exception on shutting down task " + task.getId() + ": " + e);
            }
            Thread thread = runner.getRunner();
            if (thread != null) {
                thread.interrupt();
            }
        }
    }
    running.clear();
}

From source file:ch.cyberduck.core.transfer.TransferQueue.java

/**
 * @param t Transfer to drop from queue//from w  ww.  j  a  v a 2  s  . c o  m
 */
public void remove(final Transfer t) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Remove %s from queue", t));
    }
    if (running.remove(t)) {
        if (0 == running.size()) {
            label.badge(StringUtils.EMPTY);
        } else {
            label.badge(String.valueOf(running.size()));
        }
    } else {
        final Thread removed = threads.remove(t);
        if (removed != null) {
            log.warn(String.format("Interrupt thread %s for transfer %s", removed, t));
            removed.interrupt();
        }
        temporary.remove(t);
    }
    // Transfer has finished.
    this.poll();
}

From source file:com.wolvereness.overmapped.lib.MultiProcessor.java

@Override
public void shutdown() {
    if (shutdown)
        return;//  w w w  .ja v a  2 s.c  o  m
    super.shutdown();

    final Queue<Task<?>> queue = this.queue;
    while (true) {
        final Task<?> task = queue.poll();
        if (task != null) {
            task.cancel(false);
        } else {
            break;
        }
    }
    for (final Thread thread : threads) {
        thread.interrupt();
    }
}

From source file:util.HttpUrlUtils.java

public String getContent(String url) throws HttpErrException {
    byte[] buf = new byte[1024];
    byte[] result = new byte[0];
    int length = 0;
    try {/* w w w.jav  a  2 s  . co  m*/
        ContentStream contentStream = new ContentStream();
        Thread urlThread = new URLThread(contentStream, url);
        urlThread.start();
        URLConnection conn = contentStream.get();
        try {
            urlThread.interrupt();
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw new HttpErrException("Could not get the content of the URL: ", e);
        }
        if (conn == null)
            return null;
        InputStream is = conn.getInputStream();
        while ((length = is.read(buf)) != -1) {
            byte[] temp = new byte[result.length + length];
            System.arraycopy(result, 0, temp, 0, result.length);
            System.arraycopy(buf, 0, temp, result.length, length);
            result = temp;
        }
    } catch (Exception e) {
        throw new HttpErrException("Could not get the content of the URL: " + url.toString(), e);
    }
    logger.info("content size (in bytes) = " + result.length);
    return new String(result);
}