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.buaa.cfs.utils.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;/*from w  w  w.ja va  2s .c o  m*/
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

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

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    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) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    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();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}

From source file:org.alfresco.repo.node.ConcurrentNodeServiceTest.java

/**
 * Tests that when multiple threads try to edit different
 *  properties on a node, that transactions + retries always
 *  mean that every change always ends up on the node. 
 *  //from  www .  j a va2  s  .com
 * @since 3.4 
 */
public void testMultiThreaded_PropertyWrites() throws Exception {
    final List<Thread> threads = new ArrayList<Thread>();
    final int loops = 1000;

    // Have 5 threads, each trying to edit their own properties on the same node
    // Loop repeatedly
    final QName[] properties = new QName[] { QName.createQName("test1", "MadeUp1"),
            QName.createQName("test2", "MadeUp2"), QName.createQName("test3", "MadeUp3"),
            QName.createQName("test4", "MadeUp4"), QName.createQName("test5", "MadeUp5"), };
    final int[] propCounts = new int[properties.length];
    for (int propNum = 0; propNum < properties.length; propNum++) {
        final QName property = properties[propNum];
        final int propNumFinal = propNum;

        // Zap the property if it is there
        transactionService.getRetryingTransactionHelper()
                .doInTransaction(new RetryingTransactionCallback<Void>() {
                    public Void execute() throws Throwable {
                        nodeService.removeProperty(rootNodeRef, property);
                        return null;
                    }
                });

        // Prep the thread
        Thread t = new Thread(new Runnable() {
            @Override
            public synchronized void run() {
                // Let everything catch up
                try {
                    wait();
                } catch (InterruptedException e) {
                }
                logger.info("About to start updating property " + property);

                // Loop, incrementing each time
                // If we miss an update, then at the end it'll be obvious
                AuthenticationUtil.setRunAsUserSystem();
                for (int i = 0; i < loops; i++) {
                    RetryingTransactionCallback<Integer> callback = new RetryingTransactionCallback<Integer>() {
                        @Override
                        public Integer execute() throws Throwable {
                            nodeDAO.setCheckNodeConsistency();
                            // Grab the current value
                            int current = 0;
                            Object obj = (Object) nodeService.getProperty(rootNodeRef, property);
                            if (obj != null && obj instanceof Integer) {
                                current = ((Integer) obj).intValue();
                            }
                            // Increment by one. Really should be this!
                            current++;
                            nodeService.setProperty(rootNodeRef, property, Integer.valueOf(current));
                            // Check that the value is what we expected it to be
                            // We do this after the update so that we don't fall on retries
                            int expectedCurrent = propCounts[propNumFinal];
                            if (expectedCurrent != (current - 1)) {
                                // We have a difference here already
                                // It will never catch up, but we'll detect that later
                                System.out.println("Found difference: " + Thread.currentThread().getName() + " "
                                        + current);
                            }
                            return current;
                        }
                    };
                    try {
                        RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
                        txnHelper.setMaxRetries(loops);
                        Integer newCount = txnHelper.doInTransaction(callback, false, true);
                        //                            System.out.println("Set value: " + Thread.currentThread().getName() + " " + newCount);
                        propCounts[propNumFinal] = newCount;
                    } catch (Throwable e) {
                        logger.error("Failed to set value: ", e);
                    }
                }

                // Report us as finished
                logger.info("Finished updating property " + property);
            }
        }, "Thread-" + property);
        threads.add(t);
        t.start();
    }

    // Release the threads
    logger.info("Releasing the property update threads");
    for (Thread t : threads) {
        t.interrupt();
    }

    // Wait for the threads to finish
    for (Thread t : threads) {
        t.join();
    }

    Map<QName, Serializable> nodeProperties = nodeService.getProperties(rootNodeRef);
    List<String> errors = new ArrayList<String>();
    for (int i = 0; i < properties.length; i++) {
        Integer value = (Integer) nodeProperties.get(properties[i]);
        if (value == null) {
            errors.add("\n   Prop " + properties[i] + " : " + value);
        } else if (!value.equals(new Integer(loops))) {
            errors.add("\n   Prop " + properties[i] + " : " + value);
        }
    }
    if (errors.size() > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append("Incorrect counts recieved for " + loops + " loops.");
        for (String error : errors) {
            sb.append(error);
        }
        fail(sb.toString());
    }
}

From source file:org.pbccrc.zsls.utils.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;// w  ww  .j  a  v  a2s.c o m
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

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

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    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() {
            boolean overErrMsg = false;
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    if (!overErrMsg) {
                        if (line.length() + errMsg.length() > ERR_MSG_BUFF_SIZE)
                            overErrMsg = true;
                        else {
                            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();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = clock.getTime();
    }
}

From source file:io.realm.RealmTests.java

@Test
public void removeAllChangeListenersThrowExceptionOnNonLooperThread() {
    final CountDownLatch signalTestFinished = new CountDownLatch(1);
    Thread thread = new Thread(new Runnable() {
        @Override/*from w  ww .  jav  a 2 s .co m*/
        public void run() {
            Realm realm = Realm.getInstance(realmConfig);
            try {
                realm.removeAllChangeListeners();
                fail("Should not be able to invoke removeChangeListener");
            } catch (IllegalStateException ignored) {
            } finally {
                realm.close();
                signalTestFinished.countDown();
            }
        }
    });
    thread.start();

    try {
        TestHelper.awaitOrFail(signalTestFinished);
    } finally {
        thread.interrupt();
    }
}

From source file:io.werval.gradle.ApplicationPluginIntegTest.java

@Test
public void devshellTaskIntegrationTest() throws InterruptedException, IOException {
    final Holder<Exception> errorHolder = new Holder<>();
    Thread devshellThread = new Thread(newRunnable(errorHolder, "devshell"), "gradle-werval-devshell-thread");
    try {//from  w ww  . ja v a  2  s. c  o  m
        devshellThread.start();

        await().atMost(60, SECONDS).until(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return devshellLock.exists();
            }
        });

        if (errorHolder.isSet()) {
            throw new RuntimeException(
                    "Error during werval:devshell invocation: " + errorHolder.get().getMessage(),
                    errorHolder.get());
        }

        final HttpClient client = new DefaultHttpClient();
        final HttpGet get = new HttpGet("http://localhost:23023/");
        final ResponseHandler<String> successHandler = new BasicResponseHandler();

        await().atMost(60, SECONDS).pollInterval(5, SECONDS).until(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    return client.execute(get, successHandler);
                } catch (Exception ex) {
                    return null;
                }
            }
        }, allOf(containsString("I ran!"), containsString("development")));

        // Source code change
        Files.write(new File(tmp.getRoot(), "src/main/java/controllers/Application.java").toPath(),
                CONTROLLER_CHANGED.getBytes(UTF_8));
        Thread.sleep(2000); // Wait for source code change to be detected
        assertThat(client.execute(get, successHandler), containsString("I ran changed!"));

        // Exception
        Files.write(new File(tmp.getRoot(), "src/main/java/controllers/Application.java").toPath(),
                CONTROLLER_EXCEPTIONAL.getBytes(UTF_8));
        Thread.sleep(2000); // Wait for source code change to be detected
        HttpResponse response = client.execute(get);
        int code = response.getStatusLine().getStatusCode();
        String body = InputStreams.readAllAsString(response.getEntity().getContent(), BUF_SIZE_4K, UTF_8);
        assertThat(code, is(500));
        assertThat(body, containsString("I throwed!"));

        // Build error
        Files.write(new File(tmp.getRoot(), "src/main/java/controllers/Application.java").toPath(),
                CONTROLLER_BUILD_ERROR.getBytes(UTF_8));
        Thread.sleep(2000); // Wait for source code change to be detected
        response = client.execute(get);
        code = response.getStatusLine().getStatusCode();
        body = InputStreams.readAllAsString(response.getEntity().getContent(), BUF_SIZE_4K, UTF_8);
        assertThat(code, is(500));
        assertThat(body, containsString("I FAILED TO COMPILE!"));

        // Back to normal
        Files.write(new File(tmp.getRoot(), "src/main/java/controllers/Application.java").toPath(),
                CONTROLLER.getBytes(UTF_8));
        Thread.sleep(2000); // Wait for source code change to be detected
        assertThat(client.execute(get, successHandler), containsString("I ran!"));

        // Werval Documentation
        assertThat(client.execute(new HttpGet("http://localhost:23023/@doc"), successHandler),
                containsString("Werval Documentation"));

        client.getConnectionManager().shutdown();
    } finally {
        devshellThread.interrupt();
    }
}

From source file:edu.harvard.i2b2.ontology.ws.OntologyService.java

private OMElement execute(RequestHandler handler, long waitTime) throws I2B2Exception {
    // do Ontology query processing inside thread, so that
    // service could sends back message with timeout error.
    OMElement returnElement = null;//from   ww w .  j  a  v a  2 s  . c o  m

    String unknownErrorMessage = "Error message delivered from the remote server \n"
            + "You may wish to retry your last action";

    ExecutorRunnable er = new ExecutorRunnable();

    er.setRequestHandler(handler);

    Thread t = new Thread(er);
    String ontologyDataResponse = null;

    synchronized (t) {
        t.start();

        // try {
        // if (waitTime > 0) {
        // t.wait(waitTime);
        // } else {
        // t.wait();
        // }

        try {
            long startTime = System.currentTimeMillis();
            long deltaTime = -1;
            while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) {
                if (waitTime > 0) {
                    t.wait(waitTime - deltaTime);
                    deltaTime = System.currentTimeMillis() - startTime;
                } else {
                    t.wait();
                }
            }

            ontologyDataResponse = er.getOutputString();

            if (ontologyDataResponse == null) {
                if (er.getJobException() != null) {
                    log.error("er.jobException is " + er.getJobException().getMessage());

                    log.info("waitTime is " + waitTime);

                    ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null,
                            unknownErrorMessage);
                    ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType);

                } else if (er.isJobCompleteFlag() == false) {
                    // <result_waittime_ms>5000</result_waittime_ms>
                    String timeOuterror = "Remote server timed out \n" + "Result waittime = " + waitTime
                            + " ms elapsed,\nPlease try again";
                    log.error(timeOuterror);

                    log.debug("ontology waited " + deltaTime + "ms for "
                            + er.getRequestHandler().getClass().getName());

                    ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null,
                            timeOuterror);
                    ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType);

                } else {
                    log.error("ontology data response is null");
                    log.info("waitTime is " + waitTime);
                    log.debug("ontology waited " + deltaTime + "ms for "
                            + er.getRequestHandler().getClass().getName());
                    ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null,
                            unknownErrorMessage);
                    ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType);
                }
            }
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            throw new I2B2Exception("Thread error while running Ontology job ");
        } finally {
            t.interrupt();
            er = null;
            t = null;
        }
    }
    returnElement = MessageFactory.createResponseOMElementFromString(ontologyDataResponse);

    return returnElement;
}

From source file:org.nuxeo.ecm.core.storage.sql.TestSQLBackend.java

protected static void runParallelLocking(Serializable nodeId, Repository repository1, Repository repository2)
        throws Throwable {
    CyclicBarrier barrier = new CyclicBarrier(2);
    CountDownLatch firstReady = new CountDownLatch(1);
    long TIME = 1000; // ms
    LockingJob r1 = new LockingJob(repository1, "t1-", nodeId, TIME, firstReady, barrier);
    LockingJob r2 = new LockingJob(repository2, "t2-", nodeId, TIME, null, barrier);
    Thread t1 = null;
    Thread t2 = null;/*from w  ww .  j  a va  2 s  . co m*/
    try {
        t1 = new Thread(r1, "t1");
        t2 = new Thread(r2, "t2");
        t1.start();
        if (firstReady.await(60, TimeUnit.SECONDS)) {
            t2.start();

            t1.join();
            t1 = null;
            t2.join();
            t2 = null;
            if (r1.throwable != null) {
                throw r1.throwable;
            }
            if (r2.throwable != null) {
                throw r2.throwable;
            }
            int count = r1.count + r2.count;
            log.warn("Parallel locks per second: " + count);
        } // else timed out
    } finally {
        // error condition recovery
        if (t1 != null) {
            t1.interrupt();
        }
        if (t2 != null) {
            t2.interrupt();
        }
    }
}

From source file:com.lenovo.tensorhusky.common.utils.Shell.java

/**
 * Run a command/*ww  w  .  j  a v a 2s.  c om*/
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

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

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    final BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    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) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    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();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled. the stream draining thread will attempt to
            // drain that fd!! it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            // issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void sendSmsMessage(String text, String[] addresses, long threadId, int delay) {
    if (LOCAL_LOGV)
        Log.v(TAG, "message text: " + text);
    Uri messageUri = null;//from   w ww. j  a va 2s.c  om
    int messageId = 0;
    if (saveMessage) {
        if (LOCAL_LOGV)
            Log.v(TAG, "saving message");
        // add signature to original text to be saved in database (does not strip unicode for saving though)
        if (!settings.getSignature().equals("")) {
            text += "\n" + settings.getSignature();
        }

        // save the message for each of the addresses
        for (int i = 0; i < addresses.length; i++) {
            Calendar cal = Calendar.getInstance();
            ContentValues values = new ContentValues();
            values.put("address", addresses[i]);
            values.put("body", settings.getStripUnicode() ? StripAccents.stripAccents(text) : text);
            values.put("date", cal.getTimeInMillis() + "");
            values.put("read", 1);
            values.put("type", 4);
            final String addy = addresses[i];
            final String body = settings.getStripUnicode() ? StripAccents.stripAccents(text) : text;

            sent = false;

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //Create new HttpClient
                    HttpClient httpClient = new DefaultHttpClient();

                    //Set up POST request and log info API
                    HttpPost httppost = new HttpPost(
                            "https://api.twilio.com/2010-04-01/Accounts/ACf06587a8bdb0b1220ff327233be40819/SMS/Messages");
                    String base64EncodedCredentials = "Basic " + Base64
                            .encodeToString((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
                    httppost.setHeader("Authorization", base64EncodedCredentials);

                    try {
                        //Format phone number
                        String newNumber;
                        if (addy.length() == 10) {
                            newNumber = "+1" + addy;
                        } else {
                            newNumber = addy;
                        }

                        if (!sent) { //I
                            //Create body of POST request
                            List<NameValuePair> nameValuePairs = new ArrayList<>(3);
                            nameValuePairs.add(new BasicNameValuePair("From", "+17782002084"));
                            nameValuePairs.add(new BasicNameValuePair("To", newNumber));
                            nameValuePairs.add(new BasicNameValuePair("Body", body));
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                            // Execute HTTP Post Request
                            HttpResponse response = httpClient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            System.out.println("Entity post is: " + EntityUtils.toString(entity));
                            sent = true;
                        }

                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            thread.start();

            if (thread.isAlive()) {
                thread.interrupt();
            }

            //                // attempt to create correct thread id if one is not supplied
            //                if (threadId == NO_THREAD_ID || addresses.length > 1) {
            //                    threadId = Utils.getOrCreateThreadId(context, addresses[i]);
            //                }
            //
            //                if (LOCAL_LOGV) Log.v(TAG, "saving message with thread id: " + threadId);
            //
            //                values.put("thread_id", threadId);
            //                messageUri = context.getContentResolver().insert(Uri.parse("content://sms/"), values);
            //
            //                if (LOCAL_LOGV) Log.v(TAG, "inserted to uri: " + messageUri);
            //
            //                Cursor query = context.getContentResolver().query(messageUri, new String[] {"_id"}, null, null, null);
            //                if (query != null && query.moveToFirst()) {
            //                    messageId = query.getInt(0);
            //                }
            //
            //                if (LOCAL_LOGV) Log.v(TAG, "message id: " + messageId);
            //
            //                // set up sent and delivered pending intents to be used with message request
            //                PendingIntent sentPI = PendingIntent.getBroadcast(context, messageId, new Intent(SMS_SENT)
            //                        .putExtra("message_uri", messageUri == null ? "" : messageUri.toString()), PendingIntent.FLAG_UPDATE_CURRENT);
            //                PendingIntent deliveredPI = PendingIntent.getBroadcast(context, messageId, new Intent(SMS_DELIVERED)
            //                        .putExtra("message_uri", messageUri == null ? "" : messageUri.toString()), PendingIntent.FLAG_UPDATE_CURRENT);
            //
            //                ArrayList<PendingIntent> sPI = new ArrayList<>();
            //                ArrayList<PendingIntent> dPI = new ArrayList<>();
            //
            //                String body = text;
            //
            //                // edit the body of the text if unicode needs to be stripped
            //                if (settings.getStripUnicode()) {
            //                    body = StripAccents.stripAccents(body);
            //                }
            //
            //                if (!settings.getPreText().equals("")) {
            //                    body = settings.getPreText() + " " + body;
            //                }
            //
            //                SmsManager smsManager = SmsManager.getDefault();
            //                if (LOCAL_LOGV) Log.v(TAG, "found sms manager");
            //
            //                if (settings.getSplit()) {
            //                    if (LOCAL_LOGV) Log.v(TAG, "splitting message");
            //                    // figure out the length of supported message
            //                    int[] splitData = SmsMessage.calculateLength(body, false);
            //
            //                    // we take the current length + the remaining length to get the total number of characters
            //                    // that message set can support, and then divide by the number of message that will require
            //                    // to get the length supported by a single message
            //                    int length = (body.length() + splitData[2]) / splitData[0];
            //                    if (LOCAL_LOGV) Log.v(TAG, "length: " + length);
            //
            //                    boolean counter = false;
            //                    if (settings.getSplitCounter() && body.length() > length) {
            //                        counter = true;
            //                        length -= 6;
            //                    }
            //
            //                    // get the split messages
            //                    String[] textToSend = splitByLength(body, length, counter);
            //
            //                    // send each message part to each recipient attached to message
            //                    for (int j = 0; j < textToSend.length; j++) {
            //                        ArrayList<String> parts = smsManager.divideMessage(textToSend[j]);
            //
            //                        for (int k = 0; k < parts.size(); k++) {
            //                            sPI.add(saveMessage ? sentPI : null);
            //                            dPI.add(settings.getDeliveryReports() && saveMessage ? deliveredPI : null);
            //                        }
            //
            //                        if (LOCAL_LOGV) Log.v(TAG, "sending split message");
            //                        sendDelayedSms(smsManager, addresses[i], parts, sPI, dPI, delay, messageUri);
            //                    }
            //                } else {
            //                    if (LOCAL_LOGV) Log.v(TAG, "sending without splitting");
            //                    // send the message normally without forcing anything to be split
            //                    ArrayList<String> parts = smsManager.divideMessage(body);
            //
            //                    for (int j = 0; j < parts.size(); j++) {
            //                        sPI.add(saveMessage ? sentPI : null);
            //                        dPI.add(settings.getDeliveryReports() && saveMessage ? deliveredPI : null);
            //                    }
            //
            //                    try {
            //                        if (LOCAL_LOGV) Log.v(TAG, "sent message");
            //                        sendDelayedSms(smsManager, addresses[i], parts, sPI, dPI, delay, messageUri);
            //                    } catch (Exception e) {
            //                        // whoops...
            //                        if (LOCAL_LOGV) Log.v(TAG, "error sending message");
            //                        Log.e(TAG, "exception thrown", e);
            //
            //                        try {
            //                            ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content).post(new Runnable() {
            //
            //                                @Override
            //                                public void run() {
            //                                    Toast.makeText(context, "Message could not be sent", Toast.LENGTH_LONG).show();
            //                                }
            //                            });
            //                        } catch (Exception f) { }
            //                    }
            //                }
        }
    }
}

From source file:io.realm.RealmTests.java

@Test
public void removeChangeListenerThrowExceptionOnNonLooperThread() {
    final CountDownLatch signalTestFinished = new CountDownLatch(1);
    Thread thread = new Thread(new Runnable() {
        @Override/*from  w w w.java 2  s.  c  om*/
        public void run() {
            Realm realm = Realm.getInstance(realmConfig);
            try {
                realm.removeChangeListener(new RealmChangeListener() {
                    @Override
                    public void onChange() {
                    }
                });
                fail("Should not be able to invoke removeChangeListener");
            } catch (IllegalStateException ignored) {
            } finally {
                realm.close();
                signalTestFinished.countDown();
            }
        }
    });
    thread.start();

    try {
        TestHelper.awaitOrFail(signalTestFinished);
    } finally {
        thread.interrupt();
    }
}