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.silverpeas.core.util.DBUtilIT.java

@Test
public void nextUniqueIdUpdateForAnExistingTableShouldWorkAndConcurrency()
        throws SQLException, InterruptedException {
    int nextIdBeforeTesting = actualMaxIdInUniqueIdFor("User");
    assertThat(nextIdBeforeTesting, is(1));
    int nbThreads = 2 + (int) (Math.random() * 10);
    Logger.getAnonymousLogger()//from   w  w  w.j  a  v  a 2 s  .  com
            .info("Start at " + System.currentTimeMillis() + " with " + nbThreads + " threads");
    final Thread[] threads = new Thread[nbThreads];
    for (int i = 0; i < nbThreads; i++) {
        threads[i] = new Thread(() -> {
            try {
                int nextId = DBUtil.getNextId("User", "id");
                Logger.getAnonymousLogger().info("Next id is " + nextId + " at " + System.currentTimeMillis());
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }

    try {
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        int expectedNextId = nextIdBeforeTesting + nbThreads;
        Logger.getAnonymousLogger()
                .info("Verifying nextId is " + expectedNextId + " at " + System.currentTimeMillis());
        assertThat(actualMaxIdInUniqueIdFor("User"), is(expectedNextId));
    } finally {
        for (Thread thread : threads) {
            if (thread.isAlive()) {
                thread.interrupt();
            }
        }
    }
}

From source file:com.samknows.measurement.test.TestExecutor.java

public void executeTest(TestDescription td, TestResult result) {
    try {//from ww  w.  j av a  2 s  .c o m
        List<Param> params = tc.paramsManager.prepareParams(td.params);

        executingTest = TestFactory.create(td.type, params);
        if (executingTest != null) {
            getPartialResult();
            Logger.d(TestExecutor.class, "start to execute test: " + td.displayName);
            showNotification(tc.getString(R.string.ntf_running_test) + td.displayName);

            //execute the test in a new thread and kill it it it doesn't terminate after
            //Constants.WAIT_TEST_BEFORE_ABORT
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    executingTest.execute();
                }
            });
            t.start();
            t.join(Constants.WAIT_TEST_BEFORE_ABORT);
            if (t.isAlive()) {
                Logger.e(this, "Test is still runnuing after " + Constants.WAIT_TEST_BEFORE_ABORT / 1000
                        + " seconds.");
                t.interrupt();
                t = null;
            } else {
                lastTestBytes = executingTest.getNetUsage();
                result.isSuccess = executingTest.isSuccessful();
                String out = executingTest.getOutputString();
                result.addTestString(out);
                rc.addTest(executingTest.getJSONResult());
                // HACK TO INCLUDE THE JUDPJITTER RESULTS
                if (td.type.equalsIgnoreCase("latency")) {
                    String[] judp = executingTest.getOutputFields();
                    DCSStringBuilder jjitter = new DCSStringBuilder();
                    String jitter = "" + (Integer.parseInt(judp[5]) - Integer.parseInt(judp[6]));
                    String sent = "" + (Integer.parseInt(judp[9]) + Integer.parseInt(judp[10]));
                    String received = "" + (Integer.parseInt(judp[9]) - Integer.parseInt(judp[10]));
                    jjitter.append("JUDPJITTER");
                    jjitter.append(judp[1]); // TIMESTAMP
                    jjitter.append(judp[2]); // STATUS
                    jjitter.append(judp[3]); // TARGET
                    jjitter.append(judp[4]); // TARGET IP ADDRESS
                    jjitter.append(128); // PACKETSIZE
                    jjitter.append(0); // BITRATE
                    jjitter.append(0); // DURATION
                    jjitter.append(sent); // PACKETS SENT UP
                    jjitter.append(sent); // PACKETS SENT DOWN
                    jjitter.append(received); // PACKETS RECEIVED UP
                    jjitter.append(received); // PACKETS RECEIVED DOWN
                    jjitter.append(jitter); // JITTER UP
                    jjitter.append(jitter); // JITTER DOWN
                    jjitter.append(judp[5]); // AVERAGE RTT
                    result.addTestString(jjitter.build());
                }

                if (result.isSuccess) {
                    tc.paramsManager.processOutParams(out, td.outParamsDescription);
                    if (executingTest.getHumanReadable() != null) {
                        HashMap<String, String> last_values = executingTest.getHumanReadable().getValues();
                        for (String key : last_values.keySet()) {
                            String value = last_values.get(key);
                            Logger.d(TestExecutor.class, "last_" + key + " " + value);
                            AppSettings.getInstance().saveString("last_" + key, value);
                        }
                    }
                }

                Logger.d(TAG, "finished execution test: " + td.type);
            }
        } else {
            Logger.e(TAG, "Can't find test for: " + td.type, new RuntimeException());
            result.isSuccess = false;
        }
    } catch (Throwable e) {
        Logger.e(this, "Error in executing the test. ", e);
        result.isSuccess = false;
    } finally {
        cancelNotification();
    }
}

From source file:org.apache.torque.oid.IDBroker.java

/**
 * Shuts down the IDBroker thread./*from  ww  w  .  ja  v  a 2 s  .  c  om*/
 *
 * Calling this method stops the thread that was started for this
 * instance of the IDBroker.
 */
public void stop() {
    if (houseKeeperThread != null) {
        Thread localHouseKeeperThread = houseKeeperThread;
        houseKeeperThread = null;
        localHouseKeeperThread.interrupt();
    }
    ids.clear();
    lastQueryTime.clear();
    quantityStore.clear();
    transactionsSupported = false;
}

From source file:org.apache.hadoop.yarn.applications.amonly.TestDistributedShellWithNodeLabels.java

@Test(timeout = 90000)
public void testDSShellWithNodeLabelExpression() throws Exception {
    initializeNodeLabels();//from w  w w .j a  va 2s.  com

    // Start NMContainerMonitor
    NMContainerMonitor mon = new NMContainerMonitor();
    Thread t = new Thread(mon);
    t.start();

    // Submit a job which will sleep for 60 sec
    String[] args = { "--jar", TestDistributedShell.APPMASTER_JAR, "--num_containers", "4", "--shell_command",
            "sleep", "--shell_args", "15", "--master_memory", "512", "--master_vcores", "2",
            "--container_memory", "128", "--container_vcores", "1", "--node_label_expression", "x" };

    LOG.info("Initializing DS Client");
    final Client client = new Client(new Configuration(distShellTest.yarnCluster.getConfig()));
    boolean initSuccess = client.init(args);
    Assert.assertTrue(initSuccess);
    LOG.info("Running DS Client");
    boolean result = client.run();
    LOG.info("Client run completed. Result=" + result);

    t.interrupt();

    // Check maximum number of containers on each NMs
    int[] maxRunningContainersOnNMs = mon.getMaxRunningContainersReport();
    // Check no container allocated on NM[0]
    Assert.assertEquals(0, maxRunningContainersOnNMs[0]);
    // Check there're some containers allocated on NM[1]
    Assert.assertTrue(maxRunningContainersOnNMs[1] > 0);
}

From source file:org.talend.commons.utils.threading.Locker.java

/**
 * /* w w w  . j  av  a 2 s  .c om*/
 * @deprecated use instead {@link org.talend.commons.utils.threading.lockerbykey.LockerByKey}
 */
@Deprecated
public synchronized void shutdown() {
    Object[] values = waitingThreadsByKey.values().toArray(new Object[0]);
    for (Object object : values) {
        if (object instanceof List) {
            List<Thread> list = (List<Thread>) object;
            for (Thread thread : list) {
                try {
                    thread.interrupt();
                } catch (SecurityException e) {
                    log.warn(e.getMessage(), e);
                }
            }
        } else {
            try {
                ((Thread) object).interrupt();
            } catch (SecurityException e) {
                log.warn(e.getMessage(), e);
            }
        }
    }
}

From source file:com.intuit.tank.harness.APITestHarness.java

/**
 * @param cmd// w  w  w .j a v  a  2s  .c o  m
 */
public void setCommand(WatsAgentCommand newCommand) {
    if (cmd != WatsAgentCommand.stop) {
        cmd = newCommand;
        LOG.info(LogUtil.getLogMessage(
                "Got new Command: " + newCommand + " with " + currentNumThreads + " User Threads running.",
                LogEventType.System));
        if (cmd == WatsAgentCommand.stop || cmd == WatsAgentCommand.pause
                || cmd == WatsAgentCommand.pause_ramp) {
            APIMonitor.setJobStatus(cmd == WatsAgentCommand.stop ? JobStatus.Stopped
                    : cmd == WatsAgentCommand.pause ? JobStatus.Paused : JobStatus.RampPaused);
            if (cmd == WatsAgentCommand.pause) {
                for (Thread t : sessionThreads) {
                    t.interrupt();
                }
            }
        } else if (cmd == WatsAgentCommand.resume_ramp || cmd == WatsAgentCommand.run) {
            APIMonitor.setJobStatus(JobStatus.Running);
        }

    }
}

From source file:fr.cnes.sitools.extensions.astro.application.uws.jobmanager.AbstractJobTask.java

/**
 * Cancel the thread.//from  w  w  w .ja  v a  2 s.co m
 */
public final void cancel() {
    final Thread tmpBlinker = blinker;
    blinker = null;
    if (tmpBlinker != null) {
        tmpBlinker.interrupt();
    }
    this.setPhase(ExecutionPhase.ABORTED);
}

From source file:org.apparatus_templi.Coordinator.java

private static void stopDrivers() {
    Log.w(TAG, "Restarting all drivers");
    Log.d(TAG, "removing all event watchers");
    eventWatchers.clear();// w  w w  . j  a v a  2s .co  m

    for (String driverName : loadedDrivers.keySet()) {
        Driver d = loadedDrivers.get(driverName);
        Log.d(TAG, "terminating driver " + d.getName());
        d.terminate();

        // only wake sleeping drivers, not TERMINATED ones
        wakeDriver(d.getName(), false, false);
        // loadedDrivers.remove(driverName);
    }

    // Block for a few seconds to allow all drivers to finish their
    // termination procedure. Since the drivers may call methods in this
    // thread we need to do a non-blocking wait instead of using a call to
    // Thread.sleep()
    long sleepTime = System.currentTimeMillis() + (1000 * 5);
    while (sleepTime > System.currentTimeMillis()) {
    }

    int tryCount = 0;
    while (!driverThreads.isEmpty()) {
        for (Driver d : driverThreads.keySet()) {
            Thread t = driverThreads.get(d);
            if (t.getState() == Thread.State.TERMINATED) {
                Log.d(TAG, "driver " + d.getName() + " terminated");
                driverThreads.remove(d);
            } else {
                // we don't want to block forever waiting on a non-responsive driver thread
                if (tryCount == 20) {
                    Log.w(TAG, "driver " + d.getName() + " non-responsive, interrupting thread.");
                    t.interrupt();
                    // t.notifyAll();
                }

                // Something is seriously wrong if the driver has not stopped by now. We should
                // probably notify the user that the service is experiencing problems and should
                // be restarted
                if (tryCount == 30) {
                    Log.e(TAG, "driver " + d.getName() + " still non-responsive, force stopping");
                    t.stop();
                }

                Log.d(TAG, "waiting on driver " + d.getName() + " to terminate (state: "
                        + t.getState().toString() + ")");
                d.terminate();
                wakeDriver(d.getName(), false, false);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        tryCount++;
    }
    scheduledWakeUps.clear();
    loadedDrivers.clear();

    assert driverThreads.isEmpty();
    assert loadedDrivers.isEmpty();
    Log.w(TAG, "all drivers stopped");
}

From source file:org.syncany.tests.integration.scenarios.Issue429ScenarioTest.java

@Ignore
public void testSameFileDifferentNameFuzzy() throws Exception {
    for (int seed = 0; seed < 1000; seed++) {
        LocalTransferSettings testConnection = (LocalTransferSettings) TestConfigUtil
                .createTestLocalConnection();

        TestClient clientA = new TestClient("A", testConnection);
        TestClient clientB = new TestClient("B", testConnection);

        Random randomA = new Random(2 * seed);
        Random randomB = new Random(2 * seed + 1);

        Queue<String> queue = new ConcurrentLinkedQueue<>();

        activeThread A = new activeThread(randomA, clientA, queue);
        activeThread B = new activeThread(randomB, clientB, queue);
        Thread AThread = new Thread(A, "A");
        Thread BThread = new Thread(B, "B");
        try {//from  w w w  . j  a  v  a 2s.co  m
            AThread.start();
            BThread.start();
            //            int actionsA = -1;
            //            int actionsB = -1;

            for (int i = 0; i < 50; i++) {
                TestClient clientC = new TestClient("C", testConnection);
                clientC.down();
                if (!AThread.isAlive() || !BThread.isAlive()) {
                    throw new RuntimeException("One of the threads died");
                }

                FileUtils.deleteDirectory(clientC.getLocalFile(""));
                Thread.sleep(2000);
            }

            AThread.interrupt();
            BThread.interrupt();
        } catch (Exception e) {
            logger.log(Level.INFO, "Queue:" + queue.toString());
            logger.log(Level.INFO, "Something went wrong at seed: " + seed);
            throw e;
        }
        clientA.deleteTestData();
        clientB.deleteTestData();
    }
}

From source file:dk.netarkivet.archive.bitarchive.distribute.BitarchiveServer.java

public void visit(BatchTerminationMessage msg) throws ArgumentNotValid {
    ArgumentNotValid.checkNotNull(msg, "BatchTerminationMessage msg");
    log.info("Received BatchTerminationMessage: " + msg);

    try {/*from   w w w  .  ja v a 2 s . com*/
        Thread t = batchProcesses.get(msg.getTerminateID());

        // check whether the batchjob is still running.
        if (t == null) {
            log.info("The batchjob with ID '" + msg.getTerminateID()
                    + "' cannot be found, and must have terminated " + "by it self.");
            return;
        }

        // try to interrupt.
        if (t.isAlive()) {
            t.interrupt();
        }

        // wait one second, before verifying whether it is dead.
        synchronized (this) {
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                log.trace("Unimportant InterruptedException caught.", e);
            }
        }

        // Verify that is dead, or log that it might have a problem. 
        if (t.isAlive()) {
            log.error("The thread '" + t + "' should have been terminated,"
                    + " but it is apparently still alive.");
        } else {
            log.info("The batchjob with ID '" + msg.getTerminateID() + "' has successfully been terminated!");
        }
    } catch (Throwable e) {
        // log problem and set to NotOK!
        log.error("An error occured while trying to terminate " + msg.getTerminateID(), e);
    }
}