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.dataartisans.queryablestatedemo.BumpEventGeneratorSource.java

@Override
public void run(SourceContext<BumpEvent> sourceContext) throws Exception {
    final Random rand = new Random();
    final AtomicLong count = new AtomicLong();

    Thread throughputLogger = null;
    if (printThroughput) {
        throughputLogger = new Thread(new ThroughputLogger(count), "ThroughputLogger");
        throughputLogger.start();//from  w w w. jav  a 2  s  .c  o  m
    }

    try {
        while (running) {
            // Generate random events
            final int userId = rand.nextInt(Integer.MAX_VALUE);

            final String itemCase = RandomStringUtils.randomAlphanumeric(ITEM_ID_NUM_CHARS).toLowerCase();

            synchronized (sourceContext.getCheckpointLock()) {
                sourceContext.collect(new BumpEvent(userId, itemCase));
            }

            // Increment count for throughput logger
            count.incrementAndGet();

            Thread.yield();
        }
    } finally {
        if (throughputLogger != null) {
            throughputLogger.interrupt();
            throughputLogger.join();
        }
    }
}

From source file:org.hyperic.hq.measurement.server.session.AvailabilityCacheTest.java

public void testCacheTransactionThreads() throws Exception {
    Thread thread = new Thread() {
        public void run() {
            int id = 0;
            cache.beginTran();//from   w  w  w . jav  a  2  s .  com
            DataPoint dp = new DataPoint(id, 1.0, 1);
            cache.put(new Integer(id), dp);
            dp = new DataPoint(id, 1.0, 2);
            cache.put(new Integer(id), dp);
            cache.commitTran();
        }
    };
    thread.start();

    int id = 0;
    cache.beginTran();
    DataPoint dp = new DataPoint(id, 1.0, 3);
    cache.put(new Integer(id), dp);
    dp = new DataPoint(id, 1.0, 4);
    cache.put(new Integer(id), dp);
    cache.rollbackTran();

    // don't want to hang the build
    thread.join(5000);
    if (thread.isAlive()) {
        thread.interrupt();
        assertTrue(false);
        return;
    }

    DataPoint curr = (DataPoint) cache.get(new Integer(id));
    assertTrue(2 == curr.getTimestamp());
}

From source file:org.apache.tinkerpop.gremlin.driver.ResultQueueTest.java

@Test
public void shouldNotBeEmptyUntilError() throws Exception {
    final Thread t = addToQueue(100, 10, true, false, 1);
    try {/*from  ww w.j  av  a  2  s  .  c o m*/
        assertThat(resultQueue.isEmpty(), is(false));
        assertThat(readCompleted.isDone(), is(false));

        final Exception theProblem = new Exception();
        resultQueue.markError(theProblem);
        assertThat(readCompleted.isDone(), is(true));

        try {
            resultQueue.isEmpty();
            fail("Should have thrown an exception");
        } catch (Exception ex) {
            assertEquals(theProblem, ex.getCause());
        }
    } finally {
        t.interrupt();
    }
}

From source file:com.mirth.connect.donkey.server.channel.DestinationConnector.java

public void halt() throws ConnectorTaskException, InterruptedException {
    updateCurrentState(DeployedState.STOPPING);

    if (MapUtils.isNotEmpty(queueThreads)) {
        for (Thread thread : queueThreads.values()) {
            thread.interrupt();
        }/*from  w ww  . ja  v a 2 s. c om*/
    }

    try {
        onHalt();
    } finally {
        if (MapUtils.isNotEmpty(queueThreads)) {
            try {
                for (Thread thread : queueThreads.values()) {
                    thread.join();
                }

                queueThreads.clear();
            } finally {
                // Invalidate the queue's buffer when the queue is stopped to prevent the buffer becoming 
                // unsynchronized with the data store.
                queue.invalidate(false, true);
            }
        }

        channel.getEventDispatcher().dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
        updateCurrentState(DeployedState.STOPPED);
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.ResultQueueTest.java

@Test
public void shouldGetSizeUntilError() throws Exception {
    final Thread t = addToQueue(100, 10, true, false, 1);
    try {/*from w  ww  .j  a v  a  2  s . c o  m*/
        assertThat(resultQueue.size(), is(greaterThan(0)));
        assertThat(readCompleted.isDone(), is(false));

        final Exception theProblem = new Exception();
        resultQueue.markError(theProblem);
        assertThat(readCompleted.isDone(), is(true));

        try {
            resultQueue.size();
            fail("Should have thrown an exception");
        } catch (Exception ex) {
            assertEquals(theProblem, ex.getCause());
        }
    } finally {
        t.interrupt();
    }
}

From source file:de.fu_berlin.inf.dpp.net.internal.StreamSession.java

/**
 * closes the session and it's streams/*from   w  ww .jav a  2  s.  c  om*/
 */
public synchronized void dispose() {
    if (disposed)
        return;
    disposed = true;
    // close streams
    closeStreams(inputStreams);
    closeStreams(outputStreams);
    // shutdown threads
    for (Thread t : resendThread) {
        if (t != null)
            t.interrupt();
    }
    if (streamServiceManager.sender != null)
        streamServiceManager.sender.removeData(this);
    streamServiceManager.sessions.remove(this.getStreamPath());
}

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

/**
 * Ensures a time limit on diagram generation of 20 seconds.
 *///from w  ww  .java2  s . c  om
protected void goDiagramGeneration(final Project p, final User u, final String hash, final Action a,
        final Diagram d) throws Exception {
    final Thread me = Thread.currentThread();
    final boolean watermark = !(u.isLicensed || p.isLicensed());
    Thread timer = new Thread(new Runnable() {

        public void run() {
            try {
                Thread.sleep(20000);
                me.interrupt();
            } catch (InterruptedException e) {
                // exit normally, the diagram is complete.
                log("Diagram completed ok", null);
            }
        }
    });

    try {
        timer.start();
        a.process(p, u, d, hash, watermark);
    } catch (InterruptedException e) {
        // run out of time.
        log("Run out of time generating diagram", null);
        throw new Kite9ProcessingException("Diagram couldn't be completed in time");
    } finally {
        timer.interrupt();
    }
}

From source file:org.apache.hadoop.hbase.regionserver.wal.AbstractTestLogRollPeriod.java

/**
 * Tests that the LogRoller perform the roll with some data in the log
 *//*from ww  w  .j  a v  a  2s. c  o m*/
@Test(timeout = 60000)
public void testWithEdits() throws Exception {
    final TableName tableName = TableName.valueOf("TestLogRollPeriodWithEdits");
    final String family = "cf";

    TEST_UTIL.createTable(tableName, family);
    try {
        HRegionServer server = TEST_UTIL.getRSForFirstRegionInTable(tableName);
        WAL log = server.getWAL(null);
        final Table table = TEST_UTIL.getConnection().getTable(tableName);

        Thread writerThread = new Thread("writer") {
            @Override
            public void run() {
                try {
                    long row = 0;
                    while (!interrupted()) {
                        Put p = new Put(Bytes.toBytes(String.format("row%d", row)));
                        p.addColumn(Bytes.toBytes(family), Bytes.toBytes("col"), Bytes.toBytes(row));
                        table.put(p);
                        row++;

                        Thread.sleep(LOG_ROLL_PERIOD / 16);
                    }
                } catch (Exception e) {
                    LOG.warn(e);
                }
            }
        };

        try {
            writerThread.start();
            checkMinLogRolls(log, 5);
        } finally {
            writerThread.interrupt();
            writerThread.join();
            table.close();
        }
    } finally {
        TEST_UTIL.deleteTable(tableName);
    }
}

From source file:tayler.TailerTest.java

@Test
public void testOverwriteWithMoreDataIgnoresInitialLines() throws Exception {
    File file = new File(getTestDirectory(), "testOverwriteWithMoreDataIgnoresInitialLines.txt");
    createFile(file);// w  w w .ja v  a 2s  .  c o m

    TestTailerListener listener = new TestTailerListener();
    long delay = 50;

    tailer = new Tailer(file, listener, delay, false);

    Thread thread = new Thread(tailer);
    thread.start();

    // Write a single line:
    write(file, "Line 1");
    Thread.sleep(delay * 2);
    assertEquals("Expected one line.", 1, listener.getLines().size());

    // Rotate:
    eraseFile(file);

    // Write another line, which will be ignored because size is equal to previous one:
    write(file, "Line 2");
    // This will be read instead:
    write(file, "Line 3");
    Thread.sleep(delay * 2);
    assertEquals("Expected two lines.", 2, listener.getLines().size());
    assertEquals("Expected Line 3 value.", "Line 3", listener.getLines().get(1));

    // Stop
    tailer.stop();
    thread.interrupt();
}

From source file:com.gist.twitter.TwitterClient.java

/**
 * Divides the ids among the credentials, and starts up a thread
 * for each set of credentials with a TwitterProcessor that
 * connects to twitter, and reconnects on exceptions, and
 * processes the stream.  After processForMillis, interrupt the
 * threads and return.//  ww w  .j av  a 2s. c o  m
 */
private void processForATime() {
    Collection<String> followIds = filterParameterFetcher.getFollowIds();
    Collection<Set<String>> followIdSets = createSets(followIds, maxFollowIdsPerCredentials);

    Collection<String> trackKeywords = filterParameterFetcher.getTrackKeywords();
    Collection<Set<String>> trackKeywordSets = createSets(trackKeywords, maxTrackKeywordsPerCredentials);

    Collection<Thread> threads = new ArrayList<Thread>();

    Iterator<UsernamePasswordCredentials> credentialsIterator = credentials.iterator();

    for (Set<String> ids : followIdSets) {
        for (Collection<String> keywords : trackKeywordSets) {
            if (credentialsIterator.hasNext()) {
                UsernamePasswordCredentials upc = credentialsIterator.next();
                Thread t = new Thread(new TwitterProcessor(upc, ids, keywords), "Twitter download as "
                        + upc.getUserName() + " (" + threadCount.getAndIncrement() + ")");
                threads.add(t);
                t.start();
            } else {
                logger.warning("Out of credentials, ignoring some ids/keywords.");
            }
        }
    }

    try {
        Thread.sleep(processForMillis);
    } catch (InterruptedException ex) {
        // Won't happen, ignore.
    }

    for (Thread t : threads) {
        t.interrupt();
    }

    // It doesn't matter so much whether the threads exit in a
    // timely manner.  We'll just get some IOExceptions or
    // something and retry.  This just makes the logs a little
    // nicer since we won't usually start a thread until the old
    // one has exited.
    for (Thread t : threads) {
        try {
            t.join(1000L);
        } catch (InterruptedException ex) {
            // Won't happen.
        }
    }
}