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.jxtadoop.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    boolean completed = false;

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }/* w ww  .j av  a 2s  .co  m*/
    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:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java

/**
 * Mtodo que extra o contedo de uma pgina web.
 * // w  w w .j a v  a 2s .c  o m
 * @param url
 *            Pgina que vai ser pesquisada.
 * @return Contedo da pgina HTML.
 * @throws IOException
 *             Erro ao tentar extrair o contedo da pgina html.
 */
public void getContent(final RelatorioDaUrl relatorio) {
    /*
     * Melhorar este cdigo!!! 
     */
    log.addLog("getContent(" + relatorio.getUrl() + ")\n");
    int status = 9999;
    setAtivo(false);
    metodo = null;
    final int mb = 1024;

    String type = new String();
    InputStream ist = null;
    StringBuilder sbd = null;

    setPaginaObtida(true);

    TimeOut tc = new TimeOut(this);

    setAtivo(true);
    Thread thrTc = new Thread(tc);
    thrTc.start();
    try {
        metodo = new GetMethod(relatorio.getUrl());
        metodo.setRequestHeader("user-agent", "Mozilla/5.0");
        metodo.setFollowRedirects(true);
    } catch (Exception e) {
        log.addLog("Erro no GetMetodo: " + e.getMessage() + "\n");
        //Ini - nati code
        colocaNaTabelaErros("timeOut", relatorio);
        setPaginaObtida(false);
        setAtivo(false);
        //Fim - nati code
        metodo = null;
        thrTc = null;
        tc = null;
        return;
    }
    if (!tc.timeOut) {
        // httpClient.setConnectionTimeout(arg0)
        try {
            status = httpClient.executeMethod(metodo);
            type = getContentType(metodo);
            String tam = getContentLength(metodo);
            String location = getLocation(metodo);
            if (location != "") {
                //System.out.print(relatorio.getUrl()+" to "+location+"\n");
            }
            log.addLog("type=" + type + " tam=" + tam + "\n");
            if ((status == HttpStatus.SC_OK) && (type.toUpperCase().indexOf("TEXT/HTML") > -1)) {
                if (!tc.timeOut) {
                    sbd = new StringBuilder();
                    //ist = metodo.getResponseBodyAsStream();
                } else {
                    colocaNaTabelaErros("timeOut", relatorio);
                    setPaginaObtida(false);
                    if (!thrTc.interrupted())
                        if (thrTc.isAlive())
                            thrTc.interrupt();
                    setAtivo(false);
                }

                if (!tc.timeOut) {
                    /*
                    byte[] dados = new byte[mb];
                    int bytesLidos = 0;
                            
                    while ((bytesLidos = ist.read(dados)) > 0) {
                       sbd.append(new String(dados, 0, bytesLidos));
                    }
                            
                    ist.close();
                    */
                    sbd.append(metodo.getResponseBodyAsString());
                } else {
                    colocaNaTabelaErros("timeOut", relatorio);
                    setPaginaObtida(false);
                    if (!thrTc.interrupted())
                        if (thrTc.isAlive())
                            thrTc.interrupt();
                    setAtivo(false);
                }
                //verifica se existe contedo
                if (sbd.toString().equals("") || sbd == null || sbd.toString().trim().length() <= 1) {
                    colocaNaTabelaErros("Sem contedo", relatorio);
                    setPaginaObtida(false);
                    if (!thrTc.interrupted())
                        if (thrTc.isAlive())
                            thrTc.interrupt();
                    setAtivo(false);
                }
            } else {
                //verifica se o tipo est errado
                if (type.toUpperCase().indexOf("TEXT/HTML") == -1) {
                    colocaNaTabelaErros("No HTML", relatorio);
                } else if (status == HttpStatus.SC_NOT_FOUND) {
                    colocaNaTabelaErros("No Encontrado", relatorio);
                } else {
                    colocaNaTabelaErros("Status error " + status, relatorio);
                }
                setPaginaObtida(false);
                if (!thrTc.interrupted())
                    if (thrTc.isAlive())
                        thrTc.interrupt();
                setAtivo(false);
            }

            if (!tc.timeOut) {
                metodo.abort();
                metodo.releaseConnection();
            } else {
                colocaNaTabelaErros("timeOut", relatorio);
                setAtivo(false);
                setPaginaObtida(false);
                if (!thrTc.interrupted())
                    if (thrTc.isAlive())
                        thrTc.interrupt();
            }

            if (!thrTc.interrupted())
                if (thrTc.isAlive())
                    thrTc.interrupt();

        } catch (Exception e) {
            log.addLog("Erro: " + e.getMessage() + "\n");
            colocaNaTabelaErros("Erro: " + e.getMessage(), relatorio);
            setAtivo(false);
            setPaginaObtida(false);
            if (!thrTc.interrupted())
                if (thrTc.isAlive())
                    thrTc.interrupt();
        }
    } else {
        colocaNaTabelaErros("timeOut", relatorio);
        setPaginaObtida(false);
        setAtivo(false);
        if (!thrTc.interrupted())
            if (thrTc.isAlive())
                thrTc.interrupt();
    }
    try {
        metodo.abort();
        metodo.releaseConnection();
    } catch (Exception e) {

    }
    if (sbd != null && (type.toUpperCase().indexOf("TEXT") > -1) && !tc.timeOut && isAtivo()) {
        setAtivo(false);
        //System.out.println("PPW:\n"+sbd.toString());
        relatorio.setConteudo(sbd);
    }
    if (!tc.isTimeOut()) {
        setPaginaObtida(true);
    }

    tc.timeOut = false;
    setAtivo(false);
    if (!thrTc.interrupted())
        if (thrTc.isAlive())
            thrTc.interrupt();

    log.addLog("Ok \n");
}

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

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    final JStock m = JStock.instance();
    final IndicatorDefaultDrawing indicatorDefaultDrawing = (IndicatorDefaultDrawing) this.view.getDrawing();
    final OperatorIndicator operatorIndicator = indicatorDefaultDrawing.getOperatorIndicator();

    Stock stock = null;//w  w  w.ja  v a 2  s  . c  om
    // Check, if stock information is required.
    if (operatorIndicator.isStockNeeded() || operatorIndicator.isStockHistoryServerNeeded()) {
        final Object o = ((ObjectInspectorJPanel) this.objectInspectorJPanel).getBean();
        final MutableStock mutableStock = (MutableStock) o;
        stock = mutableStock.getStock();
        if (stock.code.toString().equals("")) {
            JOptionPane.showMessageDialog(this,
                    MessagesBundle.getString("warning_message_you_need_to_select_a_stock"),
                    MessagesBundle.getString("warning_title_you_need_to_select_a_stock"),
                    JOptionPane.WARNING_MESSAGE);
            this.jComboBox1.requestFocus();
            return;
        }
    }

    // Start button.
    this.jButton4.setEnabled(false);
    // Stop button.
    this.jButton6.setEnabled(true);

    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);
        }
    }

    final Stock tmpStock = stock;
    simulationThread = new Thread(new Runnable() {
        @Override
        public void run() {
            IndicatorPanel.this.simulate(tmpStock);
        }
    });

    simulationThread.start();
}

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

public void testServerTimeouts() throws Exception {
    final ServerSocket srvSocket = new ServerSocket(0);
    int srvPort = srvSocket.getLocalPort();
    Thread serverThread = new Thread() {
        @Override//w  w w.ja  va  2s.  c  o m
        public void run() {
            try {
                Socket clientSocket = srvSocket.accept();
                // Sleep 1s (timeout applied on client is 0.1s)
                Thread.sleep(1000);
                clientSocket.getOutputStream().write(0);
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    serverThread.setDaemon(true);
    try {
        serverThread.start();
        EmailActionExecutor email = new EmailActionExecutor();
        Context ctx = createNormalContext("email-action");
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.port", srvPort);
        // Apply a 0.1s timeout to induce a very quick "Read timed out" error
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.socket.timeout.ms",
                100);
        try {
            email.validateAndMail(ctx, prepareEmailElement(false, false));
            fail("Should have failed with a socket timeout error!");
        } catch (Exception e) {
            Throwable rootCause = e;
            while (rootCause.getCause() != null) {
                rootCause = rootCause.getCause();
            }
            assertTrue("Expected exception type to be a SocketTimeoutException, but received: " + rootCause,
                    rootCause instanceof SocketTimeoutException);
            assertTrue("Expected error to be that of a socket read timeout, but got: " + rootCause.getMessage(),
                    rootCause.getMessage().contains("Read timed out"));
        }
    } finally {
        serverThread.interrupt();
        srvSocket.close();
    }
}

From source file:org.red5.net.websocket.WebSocketServerTest.java

@Test
public void testUriWithParams() throws Throwable {
    log.info("\ntestUriWithParams enter");
    // create the server instance
    Thread server = new Thread() {
        @Override//  w w w.ja  v a 2s. co  m
        public void run() {
            log.debug("Server thread run");
            try {
                WSServer.main(null);
            } catch (Exception e) {
                log.error("Error in server thread", e);
            }
            log.debug("Server thread exit");
        }
    };
    server.setDaemon(true);
    server.start();
    // add plugin to the registry
    WebSocketPlugin plugin = new WebSocketPlugin();
    PluginRegistry.register(plugin);
    // start plugin
    plugin.doStart();
    // create a scope for the manager
    IScope appScope = new GlobalScope();
    // create an app
    MultiThreadedApplicationAdapter app = new MultiThreadedApplicationAdapter();
    app.setScope(appScope);
    // add the app
    plugin.setApplication(app);
    // get the manager
    WebSocketScopeManager manager = plugin.getManager(appScope);
    manager.setApplication(appScope);
    // wait for server
    while (!WSServer.isListening()) {
        Thread.sleep(10L);
    }
    // create the client
    final TyrusWSClient client = new TyrusWSClient();
    //final TyrusWSClient client = new TyrusWSClient(8192 * 10);
    Thread t = new Thread(new Runnable() {
        public void run() {
            client.start();
        }
    }, "tyrus");
    t.start();
    t.join(5000);
    // send a message
    //client.sendMessage("This is a test");
    // terminate client
    client.terminate();
    // stop server
    server.interrupt();
    WSServer.stop();
    // stop plugin
    PluginRegistry.shutdown();
    log.info("testUriWithParams exit");
}

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

/**
 * check the agent threads if simulation time has been met.
 *//*from ww w  .j  a v a2  s  .  c o  m*/
public void checkAgentThreads() {
    int activeCount = threadGroup.activeCount();
    Thread[] threads = new Thread[activeCount];
    threadGroup.enumerate(threads);
    int activeThreads = 0;
    for (Thread t : threads) {
        if (t != null) {
            if (t.getState() == Thread.State.TIMED_WAITING || t.getState() == Thread.State.WAITING) {
                activeThreads++;
            }
        }
    }
    LOG.info(LogUtil.getLogMessage("Have " + activeThreads + " of " + activeCount
            + " active Threads in thread group " + threadGroup.getName(), LogEventType.System));
    if (agentRunData.getSimulationTime() != 0 && hasMetSimulationTime() && doneSignal.getCount() != 0) {
        boolean exceededTimeLimit = System.currentTimeMillis() > getMaxSimulationEndTimeMillis();
        if (exceededTimeLimit) {
            LOG.info(LogUtil.getLogMessage("Max simulation time has been met and there are "
                    + doneSignal.getCount() + " threads not reporting done."));
            for (Thread t : sessionThreads) {
                if (t.isAlive()) {
                    if (exceededTimeLimit) {
                        LOG.warn(
                                LogUtil.getLogMessage(
                                        "thread " + t.getName() + '-' + t.getId()
                                                + " is still running with a State of " + t.getState().name(),
                                        LogEventType.System));
                        t.interrupt();
                        doneSignal.countDown();
                    }
                }
            }
        }
    }
}

From source file:me.spadival.podmode.PodModeService.java

@Override
public void onDestroy() {
    // Service is being killed, so make sure we release our resources
    mState = State.Stopped;//  w  ww  .  ja  v  a 2 s  . co  m
    mPodRunning = false;

    AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if ((mPodStatus == podStat.SIMPLEREMOTE || mPodStatus == podStat.ADVANCEDHACK) && am.isMusicActive()) {
        broadcastMediaButtons(KeyEvent.KEYCODE_MEDIA_STOP, null);
    }

    // Stop the timer task
    if (mMediaChangeTimer != null)
        mMediaChangeTimer.cancel();

    // Stop the main thread
    if (mMainThread != null) {
        Thread moribund = mMainThread;
        mMainThread = null;
        moribund.interrupt();
    }

    // mProvider.dropRemoteControls(true);

    relaxResources(true);
    giveUpAudioFocus();

    if (mSerialHost != null)
        mSerialHost.end();

    if (mSerialDevice != null)
        mSerialDevice.DestroyAccessory(true);

    if (mBTDevice != null)
        mBTDevice.stop();

    if (podWakeLock != null)
        podWakeLock.release();

    unregisterReceiver(mUsbReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mNotifyReceiver);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mRetriever.saveState(prefs, mNowPlaying);
    super.onDestroy();
}

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

public void halt() throws HaltException {
    /*//from  w w w.  j  a  v a2s .  c om
     * These executors must be shutdown here in order to terminate any other current task that
     * may be stuck. They will be terminated again after the synchronization lock is obtained.
     */

    if (channelExecutor != null) {
        List<Runnable> tasks = channelExecutor.shutdownNow();
        // If any tasks had not started yet, they need to be cancaelled, otherwise they will be stuck at future.get().
        for (Runnable task : tasks) {
            if (task instanceof Future) {
                ((Future<?>) task).cancel(true);
            }
        }
    }

    if (MapUtils.isNotEmpty(queueThreads)) {
        for (Thread queueThread : queueThreads.values()) {
            queueThread.interrupt();
        }
    }

    // Interrupt any dispatch threads that are currently processing
    synchronized (dispatchThreads) {
        shuttingDown = true;
        for (Thread thread : dispatchThreads) {
            thread.interrupt();
        }
    }

    List<Integer> deployedMetaDataIds = new ArrayList<Integer>();
    deployedMetaDataIds.add(0);

    for (DestinationChainProvider chainProvider : destinationChainProviders) {
        for (Integer metaDataId : chainProvider.getMetaDataIds()) {
            deployedMetaDataIds.add(metaDataId);
        }
    }

    for (Integer metaDataId : deployedMetaDataIds) {
        try {
            haltConnector(metaDataId);
        } catch (Throwable t) {
        }
    }

    synchronized (this) {
        /*
         * The channel could have been started again before after the previous interrupts, so
         * now that we have this lock we halt everything again to just in case.
         */
        if (currentState != DeployedState.STOPPED) {
            try {
                updateCurrentState(DeployedState.STOPPING);

                halt(deployedMetaDataIds);
                updateCurrentState(DeployedState.STOPPED);
            } catch (Throwable t) {
                if (t instanceof InterruptedException) {
                    throw new HaltException("Halt channel task for " + name + " (" + channelId
                            + ") terminated by another halt notification.", t);
                }
                throw new HaltException("Failed to halt channel " + name + " (" + channelId + ").", t);
            }
        } else {
            logger.warn(
                    "Failed to stop channel " + name + " (" + channelId + "): The channel is already stopped.");
        }
    }
}

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

private void halt(List<Integer> metaDataIds) throws Throwable {
    stopSourceQueue = true;/*from  w  w  w  . j a  v  a2s  .c  o m*/

    List<Runnable> tasks = channelExecutor.shutdownNow();
    // If any tasks had not started yet, they need to be cancaelled, otherwise they will be stuck at future.get().
    for (Runnable task : tasks) {
        if (task instanceof Future) {
            ((Future<?>) task).cancel(true);
        }
    }

    if (MapUtils.isNotEmpty(queueThreads)) {
        for (Thread queueThread : queueThreads.values()) {
            queueThread.interrupt();
        }
    }

    // Interrupt any dispatch threads that are currently processing
    synchronized (dispatchThreads) {
        shuttingDown = true;
        for (Thread thread : dispatchThreads) {
            thread.interrupt();
        }
    }

    Throwable firstCause = null;

    // If an exception occurs, then still proceed by stopping the rest of the connectors
    for (Integer metaDataId : metaDataIds) {
        try {
            haltConnector(metaDataId);
        } catch (InterruptedException e) {
            throw e;
        } catch (Throwable t) {
            if (t.getCause() instanceof InterruptedException) {
                throw (InterruptedException) t.getCause();
            }
            if (firstCause == null) {
                firstCause = t;
            }
        }
    }

    // In case interrupting everything didn't work, wait until all dispatch, chain, and recovery threads have finished
    final int timeout = 10;

    while (true) {
        synchronized (dispatchThreads) {
            if (dispatchThreads.size() == 0) {
                shuttingDown = true;
                /*
                 * Once the thread count reaches zero, we want to make sure that any calls to
                 * finishDispatch complete (which should release the channel's process lock and
                 * allow us to acquire it here).
                 */
                obtainAllProcessLockPermits();
                releaseAllProcessLockPermits();
                break;
            }
        }
        Thread.sleep(timeout);
    }

    while (!channelExecutor.awaitTermination(timeout, TimeUnit.MILLISECONDS))
        ;

    if (firstCause != null) {
        updateCurrentState(DeployedState.STOPPED);
        throw firstCause;
    }
}

From source file:fm.smart.r1.CreateExampleActivity.java

public void onClick(View v) {
    EditText exampleInput = (EditText) findViewById(R.id.create_example_sentence);
    EditText translationInput = (EditText) findViewById(R.id.create_example_translation);
    EditText exampleTransliterationInput = (EditText) findViewById(R.id.sentence_transliteration);
    EditText translationTransliterationInput = (EditText) findViewById(R.id.translation_transliteration);
    final String example = exampleInput.getText().toString();
    final String translation = translationInput.getText().toString();
    if (TextUtils.isEmpty(example) || TextUtils.isEmpty(translation)) {
        Toast t = Toast.makeText(this, "Example and translation are required fields", 150);
        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();//from  www .j av a 2  s. c  o m
    } else {
        final String example_language_code = Utils.LANGUAGE_MAP.get(example_language);
        final String translation_language_code = Utils.LANGUAGE_MAP.get(translation_language);
        final String example_transliteration = exampleTransliterationInput.getText().toString();
        final String translation_transliteration = translationTransliterationInput.getText().toString();

        if (LoginActivity.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // avoid
            // navigation
            // back to this?
            LoginActivity.return_to = CreateExampleActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("goal_id", goal_id);
            LoginActivity.params.put("item_id", item_id);
            LoginActivity.params.put("example", example);
            LoginActivity.params.put("translation", translation);
            LoginActivity.params.put("example_language", example_language);
            LoginActivity.params.put("translation_language", translation_language);
            LoginActivity.params.put("example_transliteration", example_transliteration);
            LoginActivity.params.put("translation_transliteration", translation_transliteration);
            startActivity(intent);
        } else {

            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Creating Example ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread create_example = new Thread() {
                public void run() {
                    // TODO make this interruptable .../*if
                    // (!this.isInterrupted())*/
                    try {
                        // TODO failures here could derail all ...
                        CreateExampleActivity.add_item_goal_result = new AddItemResult(
                                Main.lookup.addItemToGoal(Main.transport, goal_id, item_id, null));

                        Result result = null;
                        try {
                            result = Main.lookup.createExample(Main.transport, translation,
                                    translation_language_code, translation, null, null, null);
                            JSONObject json = new JSONObject(result.http_response);
                            String text = json.getString("text");
                            String translation_id = json.getString("id");
                            result = Main.lookup.createExample(Main.transport, example, example_language_code,
                                    example_transliteration, translation_id, item_id, goal_id);
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        CreateExampleActivity.create_example_result = new CreateExampleResult(result);

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    myOtherProgressDialog.dismiss();

                }
            };
            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    create_example.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    create_example.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            myOtherProgressDialog.show();
            create_example.start();
        }
    }
}