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.apache.hadoop.hdfs.TestAvatarFailover.java

@Test
public void testDatanodeStartupFailover() throws Throwable {
    setUp(false, "testDatanodeStartupFailover");
    cluster.shutDownDataNodes();/*  w  ww .ja v  a2 s. c om*/
    Thread fThread = new FailoverThread();
    fThread.setDaemon(true);
    fThread.start();
    Thread.sleep(3000);
    cluster.restartDataNodes(false);
    fThread.join(30000);
    try {
        assertTrue(passDeadDnFailover);
        assertTrue(failedOver);
    } catch (Throwable e) {
        fThread.interrupt();
        throw e;
    }
}

From source file:org.castor.cpa.test.test02.TestConcurrent.java

/**
 * This method is called by the tests and preform the actual
 * concurrent modification test.//from w w w . j a  v  a  2  s  .  c o m
 *
 * @param accessMode the access mode that is used in the concurrent
 *        modification tests
 */
private void runDirtyChecked(final AccessMode accessMode) throws Exception {
    JDOManager jdo = getJDOManager(DBNAME, MAPPING);

    OQLQuery oql;
    Sample object;
    QueryResults enumeration;

    // Open transaction in order to perform JDO operations
    _db.begin();

    // Determine if test object exists, if not create it.
    // If it exists, set the name to some predefined value
    // that this test will later override.
    oql = _db.getOQLQuery("SELECT object FROM " + Sample.class.getName() + " object WHERE id = $1");
    oql.bind(Sample.DEFAULT_ID);

    enumeration = oql.execute();
    if (enumeration.hasMore()) {
        object = (Sample) enumeration.next();
        LOG.debug("Retrieved object: " + object);
        object.setValue1(Sample.DEFAULT_VALUE_1);
        object.setValue2(Sample.DEFAULT_VALUE_2);
    } else {
        object = new Sample();
        LOG.debug("Creating new object: " + object);
        _db.create(object);
    }

    _db.commit();

    // Open a new transaction in order to conduct test
    _db.begin();

    oql.bind(new Integer(Sample.DEFAULT_ID));
    object = (Sample) oql.execute(accessMode).nextElement();
    object.setValue1(JDO_VALUE);

    // Perform direct JDBC access and override the value of that table
    if (accessMode != Database.DBLOCKED) {
        Connection conn = jdo.getConnectionFactory().createConnection();
        Statement stmt = conn.createStatement();
        stmt.execute("UPDATE test02_sample SET value1='" + JDBC_VALUE + "' " + "WHERE id=" + Sample.DEFAULT_ID);
        stmt.close();
        conn.close();
        LOG.debug("OK: Updated object from JDBC");
    } else {
        Thread th = new ConcurrentUpdateThread(jdo);
        th.start();
        synchronized (this) {
            try {
                wait(WAIT_FOR_CONCURRENT_UPDATE);
                if (th.isAlive()) {
                    th.interrupt();
                    LOG.debug("OK: Cannot update object from JDBC");
                } else {
                    LOG.error("Error: Updated object from JDBC");
                    fail("Updated test object from JDBC");
                }
            } catch (InterruptedException ex) {
            }
        }
    }

    // Commit JDO transaction, this should report object modified exception
    LOG.debug("Committing JDO update: dirty checking field modified");
    if (accessMode != Database.DBLOCKED) {
        try {
            _db.commit();
            LOG.error("Error: ObjectModifiedException not thrown");
            fail("ObjectModifiedException not thrown");
        } catch (ObjectModifiedException ex) {
            LOG.debug("OK: ObjectModifiedException thrown");
        }
    } else {
        try {
            _db.commit();
            LOG.debug("OK: ObjectModifiedException not thrown");
            // After _db.commit the concurrent update will be performed.
            // and we need to undo it.
            Connection conn = jdo.getConnectionFactory().createConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(
                    "UPDATE test02_sample SET value1='" + JDO_VALUE + "' " + "WHERE id=" + Sample.DEFAULT_ID);
            stmt.close();
            conn.close();
        } catch (ObjectModifiedException ex) {
            _db.rollback();
            LOG.error("Error: ObjectModifiedException thrown");
            fail("ObjectModifiedException not thrown");
        }
    }
}

From source file:com.azaptree.services.executor.ThreadPoolExecutor.java

@Override
protected void beforeExecute(final Thread t, final Runnable r) {
    super.beforeExecute(t, r);
    while (paused) {
        pauseLock.lock();//from  www.ja  va 2 s. co m
        try {
            while (paused) {
                unpaused.await();
            }
        } catch (final InterruptedException ie) {
            t.interrupt();
        } finally {
            pauseLock.unlock();
        }
    }
}

From source file:org.springframework.integration.jdbc.MessageGroupQueueTests.java

@Test
public void validateMgqInterruption() throws Exception {

    final MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), 1, 1);

    final AtomicReference<InterruptedException> exceptionHolder = new AtomicReference<InterruptedException>();

    Thread t = new Thread(() -> {
        queue.offer(new GenericMessage<String>("hello"));
        try {//  www  .j  av a  2 s.co m
            queue.offer(new GenericMessage<String>("hello"), 100, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            exceptionHolder.set(e);
        }
    });
    t.start();
    Thread.sleep(1000);
    t.interrupt();
    Thread.sleep(1000);
    assertTrue(exceptionHolder.get() instanceof InterruptedException);
}

From source file:com.whirlycott.cache.CacheDecorator.java

/** Shut down this cache. */
public void shutdown() {
    if (log.isDebugEnabled()) {
        log.debug(Messages.getString("CacheDecorator.shutting_down_cache") + name); //$NON-NLS-1$
    }// ww w . ja va2s . co  m
    if (Constants.BUILD_STATS_ENABLED) {
        log.info(getEfficiencyReport());
        recordKeeper.reset();
    }

    final Thread tunerThreadToKill = tunerThread;
    tunerThread = null;
    tunerThreadToKill.interrupt();
}

From source file:org.springframework.integration.jdbc.MessageGroupQueueTests.java

@Test
public void validateMgqInterruptionStoreLock() throws Exception {

    MessageGroupStore mgs = Mockito.mock(MessageGroupStore.class);
    Mockito.doAnswer(invocation -> {/*from w  ww.  j a v  a2  s  .  c o m*/
        Thread.sleep(5000);
        return null;
    }).when(mgs).addMessageToGroup(Mockito.any(Integer.class), Mockito.any(Message.class));

    MessageGroup mg = Mockito.mock(MessageGroup.class);
    Mockito.when(mgs.getMessageGroup(Mockito.any())).thenReturn(mg);
    Mockito.when(mg.size()).thenReturn(0);

    final MessageGroupQueue queue = new MessageGroupQueue(mgs, 1, 1);

    final AtomicReference<InterruptedException> exceptionHolder = new AtomicReference<InterruptedException>();

    Thread t1 = new Thread(() -> queue.offer(new GenericMessage<String>("hello")));
    t1.start();
    Thread.sleep(500);
    Thread t2 = new Thread(() -> {
        queue.offer(new GenericMessage<String>("hello"));
        try {
            queue.offer(new GenericMessage<String>("hello"), 100, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            exceptionHolder.set(e);
        }
    });
    t2.start();
    Thread.sleep(1000);
    t2.interrupt();
    Thread.sleep(1000);
    assertTrue(exceptionHolder.get() instanceof InterruptedException);
}

From source file:au.com.ish.derbydump.derbydump.main.DumpTest.java

@Test
public void theDumpTest() throws Exception {
    // Create table
    StringBuilder createTableBuffer = new StringBuilder();
    createTableBuffer.append("CREATE TABLE ");
    createTableBuffer.append(Configuration.getConfiguration().getSchemaName());
    createTableBuffer.append(".");
    createTableBuffer.append(tableName);
    createTableBuffer.append(" (");

    StringBuilder insertBuffer = new StringBuilder();
    insertBuffer.append("INSERT INTO ");
    insertBuffer.append(RESOURCE_SCHEMA_NAME);
    insertBuffer.append(".");
    insertBuffer.append(tableName);//from  ww w.  j a  va  2 s  .c  o  m
    insertBuffer.append(" VALUES (");

    for (String col : columns) {
        createTableBuffer.append(col.toUpperCase());
        //String[] c = col.split(" ");
        //insertBuffer.append(c[0].toUpperCase().trim());
        insertBuffer.append("?");
        if (!columns[columns.length - 1].equals(col)) {
            createTableBuffer.append(", ");
            insertBuffer.append(",");
        }
    }

    createTableBuffer.append(")");
    insertBuffer.append(")");

    config.setTableRewriteProperty("testSkip", "--exclude--");
    config.setTableRewriteProperty("testRename", "testRenameNew");
    config.setTruncateTables(truncate);

    File f = new File("./build/outputs/" + tableName + ".sql");
    if (f.exists()) {
        f.delete();
    }
    f.mkdirs();

    config.setOutputFilePath(f.getCanonicalPath());

    Connection connection = db.createNewConnection();
    Statement statement = connection.createStatement();
    PreparedStatement ps = null;

    try {
        statement.execute(createTableBuffer.toString());
        connection.commit();
        //config.setTableRewriteProperty("TABLE2", "--exclude--");

        for (Object o : valuesToInsert) {
            Object[] vals = (Object[]) o;
            if (vals.length > 0) {
                ps = db.getConnection().prepareStatement(insertBuffer.toString());
                for (int i = 0; i < vals.length; i++) {
                    if (vals[i] instanceof InputStream) {
                        ps.setBinaryStream(i + 1, (InputStream) vals[i]);
                    } else {
                        ps.setObject(i + 1, vals[i]);
                    }
                }
                ps.execute();
                connection.commit();
            }
        }

        OutputThread output = new OutputThread();
        Thread writer = new Thread(output, "File_Writer");
        writer.start();

        new DatabaseReader(output);
        // Let the writer know that no more data is coming
        writer.interrupt();
        writer.join();

        // Now let's read the output and see what is in it
        List<String> lines = FileUtils.readLines(f);

        assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 0;", lines.get(0));
        assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 1;",
                lines.get(lines.size() - 1));

        if (!skipped) {
            assertTrue("LOCK missing", lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;"));
            assertTrue("UNLOCK missing", lines.contains("UNLOCK TABLES;"));

            int index = lines.indexOf("LOCK TABLES `" + outputTableName + "` WRITE;");

            if (truncate) {
                assertTrue("TRUNCATE missing", lines.contains("TRUNCATE TABLE " + outputTableName + ";"));
                assertTrue("INSERT missing, got " + lines.get(index + 2),
                        lines.get(index + 2).startsWith("INSERT INTO " + outputTableName));
            } else {
                assertTrue("INSERT missing, got " + lines.get(index + 1),
                        lines.get(index + 1).startsWith("INSERT INTO " + outputTableName));
            }

            for (String s : validOutputs) {
                assertTrue("VALUES missing :" + s, lines.contains(s));
            }
        } else {
            assertTrue("LOCK missing", !lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;"));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("failed to create test data" + e.getMessage());
    } finally {
        if (ps != null) {
            ps.close();
        }
        statement.close();
        connection.close();
    }
}

From source file:abs.backend.erlang.ErlangTestDriver.java

/**
* Executes mainModule/*from  ww  w. j a v a  2s .c o  m*/
* 
* We replace the run script by a new version, which will write the Result
* to STDOUT Furthermore to detect faults, we have a Timeout process, which
* will kill the runtime system after 2 seconds
*/
private String run(File workDir, String mainModule) throws Exception {
    String val = null;
    File runFile = new File(workDir, "run");
    Files.write(RUN_SCRIPT, runFile, Charset.forName("UTF-8"));
    runFile.setExecutable(true);
    ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule);
    pb.directory(workDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();

    Thread t = new Thread(new TimeoutThread(p));
    t.start();
    // Search for result
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.startsWith("RES="))
            val = line.split("=")[1];
    }
    int res = p.waitFor();
    t.interrupt();
    if (res != 0)
        return null;
    return val;

}

From source file:org.evosuite.continuous.job.JobExecutorIntTest.java

@Test
public void testEventSequenceWhenWrongSchedule() throws InterruptedException {

    boolean storageOK = storage.isStorageOk();
    assertTrue(storageOK);//from ww w.ja  v a  2 s .com
    storageOK = storage.createNewTmpFolders();
    assertTrue(storageOK);

    List<TestsOnDisk> data = storage.gatherGeneratedTestsOnDisk();
    Assert.assertEquals(0, data.size());

    // no need to specify it, as com.examples are compiled with EvoSuite  
    String classpath = System.getProperty("java.class.path");

    int cores = 1;
    int memory = 1000;
    int minutes = 10000;

    CtgConfiguration conf = new CtgConfiguration(memory, cores, minutes, 1, false, AvailableSchedule.SIMPLE);
    final JobExecutor exe = new JobExecutor(storage, classpath, conf);

    JobDefinition simple = new JobDefinition(30, memory, Simple.class.getName(), 0, null, null);

    JobDefinition trivial = new JobDefinition(30, memory, Trivial.class.getName(), 0, null, null);

    JobDefinition ust = new JobDefinition(30, memory, UsingSimpleAndTrivial.class.getName(), 0,
            new HashSet<>(Arrays.asList(new String[] { Simple.class.getName(), Trivial.class.getName() })),
            null);

    /*
     * ust is in the middle, instead of last element.
     * still, even if the schedule is wrong, the executor should be able
     * to properly handle it 
     */
    final List<JobDefinition> jobs = Arrays.asList(simple, ust, trivial);

    exe.initExecution(jobs);

    Thread t = new Thread() {
        @Override
        public void run() {
            exe.execute(jobs);
        }
    };
    try {
        t.start();

        exe.doneWithJob(exe.pollJob());
        exe.doneWithJob(exe.pollJob());

        JobDefinition last = exe.pollJob();
        exe.doneWithJob(last);

        Assert.assertEquals(ust.cut, last.cut);
    } finally {
        t.interrupt();
    }

    storage.clean();
}

From source file:org.openspaces.maven.plugin.RunStandalonePUMojo.java

/**
 * executes the mojo.//from ww  w .  j av  a 2 s.c o  m
 */
public void executeMojo() throws MojoExecutionException, MojoFailureException {

    // Remove white spaces from ClassLoader's URLs
    ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
    try {
        Utils.changeClassLoaderToSupportWhiteSpacesRepository(currentCL);
    } catch (Exception e) {
        PluginLog.getLog().info("Unable to update ClassLoader. Proceeding with processing unit invocation.", e);
    }

    Utils.handleSecurity();
    try {
        ClassUtils.forName("com.gigaspaces.logger.GSLogConfigLoader", null).getMethod("getLoader", new Class[0])
                .invoke(null, new Object[0]);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to configure logging", e);
    }

    // get a list of project to execute in the order set by the reactor
    List<MavenProject> projects = Utils.getProjectsToExecute(reactorProjects, module);

    for (MavenProject proj : projects) {
        executePU(proj);
    }

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                for (int i = (containers.size() - 1); i >= 0; --i) {
                    containers.get(i).interrupt();
                }
            } finally {
                mainThread.interrupt();
            }
        }
    });
    while (!mainThread.isInterrupted()) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            // do nothing, simply exit
        }
    }

}