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:tayler.TailerTest.java

@Test
public void testTailer() throws Exception {
    // Create & start the Tailer
    long delay = 50;
    final File file = new File(getTestDirectory(), "testTailer.txt");
    createFile(file);/*from   w  w w .j  av  a  2 s  .c  om*/
    final TestTailerListener listener = new TestTailerListener();
    tailer = new Tailer(file, listener, delay, false);
    final Thread thread = new Thread(tailer);
    thread.start();

    // Write some lines to the file
    write(file, "Line one", "Line two");
    Thread.sleep(delay * 2);
    List<String> lines = listener.getLines();
    assertEquals("1 line count", 2, lines.size());
    assertEquals("1 line 1", "Line one", lines.get(0));
    assertEquals("1 line 2", "Line two", lines.get(1));
    listener.clear();

    // Write another line to the file
    write(file, "Line three");
    Thread.sleep(delay * 2);
    lines = listener.getLines();
    assertEquals("2 line count", 1, lines.size());
    assertEquals("2 line 3", "Line three", lines.get(0));
    listener.clear();

    // Check file does actually have all the lines
    lines = FileUtils.readLines(file);
    assertEquals("3 line count", 3, lines.size());
    assertEquals("3 line 1", "Line one", lines.get(0));
    assertEquals("3 line 2", "Line two", lines.get(1));
    assertEquals("3 line 3", "Line three", lines.get(2));

    // Delete & re-create
    file.delete();
    boolean exists = file.exists();
    String osname = System.getProperty("os.name");
    boolean isWindows = osname.startsWith("Windows");
    assertFalse("File should not exist (except on Windows)", exists && !isWindows);
    createFile(file);
    Thread.sleep(delay * 2);

    // Write another line
    write(file, "Line four");
    Thread.sleep(delay * 2);
    lines = listener.getLines();
    assertEquals("4 line count", 1, lines.size());
    assertEquals("4 line 3", "Line four", lines.get(0));
    listener.clear();

    // Stop
    tailer.stop();
    tailer = null;
    thread.interrupt();
    Thread.sleep(delay * 2);
    write(file, "Line five");
    assertEquals("4 line count", 0, listener.getLines().size());
    assertNull("Should not generate Exception", listener.exception);
    assertEquals("Expected init to be called", 1, listener.initialised.get());
    assertEquals("fileNotFound should not be called", 0, listener.notFound.get());
    assertEquals("fileRotated should be called", 1, listener.rotated.get());
    assertEquals("stop should be called", 1, listener.stopped.get());
}

From source file:org.hyperic.hq.product.util.PluginDumper.java

private void testTrack() throws PluginException, IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;//from  ww w  .j a v  a 2  s  .  c  o  m
    testTrack(this.config.plugin);

    Thread thread = new Thread() {
        public void run() {
            while (true) {
                flushLogTrackEvents();
                flushConfigTrackEvents();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("Done");
                    break;
                }
            }
        }
    };
    thread.start();
    System.out.println("hit 'q' to quit");
    while ((line = in.readLine()) != null) {
        if (line.equals("q")) {
            break;
        }
    }
    thread.interrupt();
}

From source file:org.apache.hadoop.hbase.replication.regionserver.TestGlobalThrottler.java

@Test
public void testQuota() throws IOException {
    final TableName tableName = TableName.valueOf(name.getMethodName());
    HTableDescriptor table = new HTableDescriptor(tableName);
    HColumnDescriptor fam = new HColumnDescriptor(famName);
    fam.setScope(HConstants.REPLICATION_SCOPE_SERIAL);
    table.addFamily(fam);/*w  w w.ja v  a 2s . c  o  m*/
    utility1.getAdmin().createTable(table);
    utility2.getAdmin().createTable(table);

    Thread watcher = new Thread(() -> {
        Replication replication = (Replication) utility1.getMiniHBaseCluster().getRegionServer(0)
                .getReplicationSourceService();
        AtomicLong bufferUsed = replication.getReplicationManager().getTotalBufferUsed();
        testQuotaPass = true;
        while (!Thread.interrupted()) {
            long size = bufferUsed.get();
            if (size > 0) {
                testQuotaNonZero = true;
            }
            if (size > 600) {
                // We read logs first then check throttler, so if the buffer quota limiter doesn't
                // take effect, it will push many logs and exceed the quota.
                testQuotaPass = false;
            }
            Threads.sleep(50);
        }
    });
    watcher.start();

    try (Table t1 = utility1.getConnection().getTable(tableName);
            Table t2 = utility2.getConnection().getTable(tableName)) {
        for (int i = 0; i < 50; i++) {
            Put put = new Put(ROWS[i]);
            put.addColumn(famName, VALUE, VALUE);
            t1.put(put);
        }
        long start = EnvironmentEdgeManager.currentTime();
        while (EnvironmentEdgeManager.currentTime() - start < 180000) {
            Scan scan = new Scan();
            scan.setCaching(50);
            int count = 0;
            try (ResultScanner results = t2.getScanner(scan)) {
                for (Result result : results) {
                    count++;
                }
            }
            if (count < 50) {
                LOG.info("Waiting all logs pushed to slave. Expected 50 , actual " + count);
                Threads.sleep(200);
                continue;
            }
            break;
        }
    }

    watcher.interrupt();
    Assert.assertTrue(testQuotaPass);
    Assert.assertTrue(testQuotaNonZero);
}

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  va2s  .c o  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:rpc.TestRPC.java

@Test(timeout = 30000)
public void testRPCInterrupted() throws IOException, InterruptedException {
    final Configuration conf = new Configuration();
    Server server = new RPC.Builder(conf).setProtocol(TestProtocol.class).setInstance(new TestImpl())
            .setBindAddress(ADDRESS).setPort(0).setNumHandlers(5).setVerbose(true).setSecretManager(null)
            .build();// w  w  w.  ja  v  a 2s  . c  o m

    server.start();

    int numConcurrentRPC = 200;
    InetSocketAddress addr = NetUtils.getConnectAddress(server);
    final CyclicBarrier barrier = new CyclicBarrier(numConcurrentRPC);
    final CountDownLatch latch = new CountDownLatch(numConcurrentRPC);
    final AtomicBoolean leaderRunning = new AtomicBoolean(true);
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    Thread leaderThread = null;

    for (int i = 0; i < numConcurrentRPC; i++) {
        final int num = i;
        final TestProtocol proxy = RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf);
        Thread rpcThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    barrier.await();
                    while (num == 0 || leaderRunning.get()) {
                        proxy.slowPing(false);
                    }

                    proxy.slowPing(false);
                } catch (Exception e) {
                    if (num == 0) {
                        leaderRunning.set(false);
                    } else {
                        error.set(e);
                    }

                    LOG.error(e);
                } finally {
                    latch.countDown();
                }
            }
        });
        rpcThread.start();

        if (leaderThread == null) {
            leaderThread = rpcThread;
        }
    }
    // let threads get past the barrier
    Thread.sleep(1000);
    // stop a single thread
    while (leaderRunning.get()) {
        leaderThread.interrupt();
    }

    latch.await();

    // should not cause any other thread to get an error
    assertTrue("rpc got exception " + error.get(), error.get() == null);
    server.stop();
}

From source file:com.datatorrent.stram.engine.StreamingContainer.java

public synchronized void deactivate() {
    ArrayList<Thread> activeThreads = new ArrayList<Thread>();
    ArrayList<Integer> activeOperators = new ArrayList<Integer>();

    for (Map.Entry<Integer, Node<?>> e : nodes.entrySet()) {
        Thread t = e.getValue().context.getThread();
        if (t == null || !t.isAlive()) {
            disconnectNode(e.getKey());//from   w w w.j  a  v a2 s . co  m
        } else {
            activeThreads.add(t);
            activeOperators.add(e.getKey());
            e.getValue().shutdown();
        }
    }

    try {
        Iterator<Integer> iterator = activeOperators.iterator();
        for (Thread t : activeThreads) {
            t.join(1000);
            if (!t.getState().equals(State.TERMINATED)) {
                t.interrupt();
            }
            disconnectNode(iterator.next());
        }
    } catch (InterruptedException ex) {
        logger.warn("Aborting wait for operators to get deactivated!", ex);
    }

    for (WindowGenerator wg : activeGenerators.keySet()) {
        wg.deactivate();
    }
    activeGenerators.clear();

    for (Stream stream : activeStreams.keySet()) {
        stream.deactivate();
    }
    activeStreams.clear();
}

From source file:com.datatorrent.stram.engine.StreamingContainer.java

private synchronized void undeploy(List<Integer> nodeList) {
    /**/*from   www . j av  a 2  s .  c  o m*/
     * make sure that all the operators which we are asked to undeploy are in this container.
     */
    HashMap<Integer, Node<?>> toUndeploy = new HashMap<Integer, Node<?>>();
    for (Integer operatorId : nodeList) {
        Node<?> node = nodes.get(operatorId);
        if (node == null) {
            throw new IllegalArgumentException("Node " + operatorId + " is not hosted in this container!");
        } else if (toUndeploy.containsKey(operatorId)) {
            throw new IllegalArgumentException(
                    "Node " + operatorId + " is requested to be undeployed more than once");
        } else {
            toUndeploy.put(operatorId, node);
        }
    }

    ArrayList<Thread> joinList = new ArrayList<Thread>();
    ArrayList<Integer> discoList = new ArrayList<Integer>();
    for (Integer operatorId : nodeList) {
        Thread t = nodes.get(operatorId).context.getThread();
        if (t == null || !t.isAlive()) {
            disconnectNode(operatorId);
        } else {
            joinList.add(t);
            discoList.add(operatorId);
            nodes.get(operatorId).shutdown();
        }
    }

    try {
        Iterator<Integer> iterator = discoList.iterator();
        for (Thread t : joinList) {
            t.join(1000);
            if (!t.getState().equals(State.TERMINATED)) {
                t.interrupt();
            }
            disconnectNode(iterator.next());
        }
        logger.info("Undeploy complete.");
    } catch (InterruptedException ex) {
        logger.warn("Aborting wait for operators to get deactivated!", ex);
    }

    for (Integer operatorId : nodeList) {
        nodes.remove(operatorId);
    }
}

From source file:org.cloudata.core.common.ShellCommand.java

/** Run a command */
private void runCommand() throws IOException {
    if (onlyUnix() && WINDOWS) {
        return;/*  ww w.j  av  a  2  s  .  c o m*/
    }
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    boolean completed = false;

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed = true;
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:com.juick.android.UserCenterActivity.java

private void enableJAM(final Runnable then) {
    if (!MainActivity.isJAMServiceRunning(UserCenterActivity.this)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);/*from  w  w w. j av  a2 s  .  c  o m*/
        builder.setMessage(R.string.JAMNotEnabledEnable);
        builder.setTitle(getString(R.string.JuickAdvancedFunctionality));
        builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(UserCenterActivity.this);
                sp.edit().putBoolean("enableJAMessaging", true).commit();
                MainActivity.toggleJAMessaging(UserCenterActivity.this, true);
                final ProgressDialog pd = new ProgressDialog(UserCenterActivity.this);
                dialog.cancel();
                pd.setIndeterminate(true);
                pd.setMessage(getString(R.string.WaitingForService));
                final Thread thread = new Thread() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                JAMService instance = JAMService.instance;
                                if (instance != null) {
                                    JAXMPPClient client = instance.client;
                                    if (client != null && client.loggedIn) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                pd.cancel();
                                                then.run();
                                            }
                                        });
                                    }
                                }
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                break;
                            }
                        }
                        super.run(); //To change body of overridden methods use File | Settings | File Templates.
                    }
                };
                thread.start();
                pd.setCancelable(true);
                pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        thread.interrupt();
                    }
                });
                pd.show();
            }
        });
        builder.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    } else {
        then.run();
    }
    return;
}

From source file:org.yccheok.jstock.gui.IndicatorPanel.java

private void stop() {
    final StockTask tmp = this.stockTask;

    if (tmp != null) {
        tmp.cancel(true);/*from   w w w. ja v a 2s.  c  om*/
        this.stockTask = null;
        log.info("Terminated stock task");
    }

    final Thread thread = this.simulationThread;
    // Set null to stop the simulation thread.
    this.simulationThread = null;
    if (thread != null) {
        thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException exp) {
            log.error(null, exp);
        }

        log.info("Terminated simulation thread");
    }
}