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.symbian.driver.remoting.master.TDIWrapper.java

/**
 * 
 */
public void stop() {
    Thread lKillThread = lSymbianThread;
    lSymbianThread = null;
    lKillThread.interrupt();
}

From source file:cherry.foundation.mail.SendMailBatchTest.java

@Test
public void testInterrupt() throws Exception {

    final File shutdownTrigger = new File("./shutdownTrigger.txt");
    shutdownTrigger.deleteOnExit();//from   w w  w  . j  a  v a2s  .  c  o m
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) {
                return true;
            } catch (IOException ex) {
                return false;
            }
        }
    };

    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS);
    final Thread currentThread = Thread.currentThread();
    ScheduledFuture<Boolean> interrupt = service.schedule(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            currentThread.interrupt();
            return true;
        }
    }, 2L, TimeUnit.SECONDS);

    SendMailBatch batch = create(1000L, shutdownTrigger, false);
    ExitStatus status = batch.execute();

    assertEquals(ExitStatus.NORMAL, status);
    assertTrue(future.get().booleanValue());
    assertTrue(interrupt.get().booleanValue());
    assertFalse(shutdownTrigger.exists());

    verify(bizDateTime, atLeastOnce()).now();
    verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(2L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(3L));
}

From source file:org.apache.hadoop.hbase.IntegrationTestManyRegions.java

@Test
public void testCreateTableWithRegions() throws Exception {
    CountDownLatch doneSignal = new CountDownLatch(1);
    Worker worker = new Worker(doneSignal, util.getHBaseAdmin());
    Thread t = new Thread(worker);

    LOG.info("Launching worker thread to create the table.");
    t.start();/*from  w  w  w.jav  a  2  s. c  o m*/
    boolean workerComplete = false;
    workerComplete = doneSignal.await(TIMEOUT_MINUTES, TimeUnit.MINUTES);
    if (!workerComplete) {
        t.interrupt();
        fail("Timeout limit expired.");
    }
    assertTrue("Table creation failed.", worker.isSuccess());
}

From source file:com.nesscomputing.event.amqp.AmqpEventReceiver.java

@OnStage(LifecycleStage.STOP)
void stop() throws InterruptedException {
    final Thread consumerThread = consumerThreadHolder.getAndSet(null);
    if (consumerThread != null) {
        final ExchangeConsumer exchangeConsumer = exchangeConsumerHolder.getAndSet(null);
        if (exchangeConsumer != null) {
            exchangeConsumer.shutdown();

            consumerThread.interrupt();
            consumerThread.join(500L);/*from   w ww .  j  a v  a 2  s  . c o m*/
        }
    } else {
        LOG.debug("Never started, ignoring stop()");
    }
}

From source file:org.apache.hadoop.mapred.MiniMRHACluster.java

public void shutdown() {
    waitTaskTrackers();//from ww  w.  j  a  va  2 s  .  co m
    for (int idx = 0; idx < taskTrackerList.size(); idx++) {
        TaskTrackerRunner taskTracker = taskTrackerList.get(idx);
        Thread taskTrackerThread = taskTrackerThreadList.get(idx);
        taskTracker.shutdown();
        taskTrackerThread.interrupt();
        try {
            taskTrackerThread.join();
        } catch (InterruptedException ex) {
            LOG.error("Problem shutting down task tracker", ex);
        }
    }
    for (JobTrackerHADaemon jtHaDaemon : jtHaDaemonList) {
        try {
            jtHaDaemon.stop();
        } catch (IOException ex) {
            LOG.error("Problem shutting down jobtracker HA daemon", ex);
        }
        jtHaDaemon.join();
    }
}

From source file:org.hyperic.hq.measurement.agent.server.MeasurementCommandsServer.java

private void interruptThread(Thread t) throws InterruptedException {
    if (t.isAlive()) {
        t.interrupt();
        t.join(THREAD_JOIN_WAIT);// ww w .  ja v a2s  . c  o  m

        if (t.isAlive()) {
            this.log.warn(t.getName() + " did not die within the " + "timeout period.  Killing it");
            t.stop();
        }
    }
}

From source file:at.sti2.sparkwave.SparkwaveKernel.java

/**
 * Terminates all threads corresponding to a pattern
 * @param patternId of the pattern// w  w  w .j a v  a2 s.co  m
 */
public boolean removeProcessorThread(long patternId) {

    Pattern pattern = idPatternMap.remove(patternId);
    if (pattern == null)
        return false;

    Thread thread = patternThreadMap.remove(pattern);
    if (thread == null)
        return false;

    logger.debug("Interrupting {}", thread);
    thread.interrupt();

    Queue<Triple> queue = patternQueueMap.remove(pattern);
    if (queue != null) {
        logger.debug("Removing queue {} from queues", queue);
        //synchronized because it might happen that StreamParserThread is iterating over queues
        synchronized (queues) {
            queues.remove(queue);
        }
    }

    return true;
}

From source file:com.serphacker.serposcope.task.google.GoogleTask.java

protected void interruptThreads() {
    interrupted = true;
    for (Thread thread : threads) {
        thread.interrupt();
    }
}

From source file:uk.co.gidley.jmxmonitor.services.ThreadManager.java

private void restartMonitoringGroup(String groupName, Configuration config)
        throws InterruptedException, InitialisationException {
    logger.warn("Monitoring Group is dead: {}. Restarting", groupName);

    // Tidy up//  w w  w . java  2  s  .  c  o m
    Thread oldThread = monitoringGroups.get(groupName).getThread();
    if (oldThread.isAlive()) {
        // Problem try to interrupt. This should force an exist
        oldThread.interrupt();
        oldThread.join(5000);
        if (oldThread.isAlive()) {
            logger.error("Unable to stop monitor thread {}", groupName);
            throw new RuntimeException("Unable to stop monitor thread " + groupName);
        }
    }
    monitoringGroups.remove(groupName);

    // Restart
    initialiseMonitoringGroup(groupName, config);
    Thread restartThread = monitoringGroups.get(groupName).getThread();
    restartThread.start();
}

From source file:ubic.gemma.core.security.audit.AuditAdviceTest.java

@SuppressWarnings("Duplicates") // Not in this project
@Test/* w  w w  .  java 2 s. co m*/
public void testAuditFindOrCreateConcurrentTorture() throws Exception {
    int numThreads = 14; // too high and we run out of connections, which is not what we're testing.
    final int numExperimentsPerThread = 5;
    final int numUpdates = 10;
    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.sleep(random.nextInt(100));

        Thread k = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int j = 0; j < numExperimentsPerThread; j++) {
                        log.debug("Starting experiment " + j);
                        ExpressionExperiment ee = ExpressionExperiment.Factory.newInstance();
                        ee.setDescription("From test");
                        ee.setShortName(RandomStringUtils.randomAlphabetic(20));
                        ee.setName(RandomStringUtils.randomAlphabetic(20));
                        ee.setTaxon(taxonService.load(1L));
                        ee = expressionExperimentService.findOrCreate(ee);

                        assertNotNull(ee.getAuditTrail());
                        assertEquals(1, ee.getAuditTrail().getEvents().size());
                        assertNotNull(ee.getCurationDetails());
                        assertNotNull(ee.getCurationDetails().getId());
                        assertNotNull(ee.getCurationDetails().getLastUpdated());
                        assertNotNull(ee.getAuditTrail().getCreationEvent().getId());

                        for (int q = 0; q < numUpdates; q++) {
                            Thread.sleep(random.nextInt(5));
                            log.debug("Update: experiment " + j);
                            expressionExperimentService.update(ee);
                            c.incrementAndGet();
                        }
                        log.debug("Done with experiment " + j);
                    }
                } 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 * numExperimentsPerThread * numUpdates;
    while (c.get() < expectedEventCount && !failed.get()) {
        Thread.sleep(1000);
        log.info("Waiting ...");
        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!");
    }

}