Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:org.apache.hadoop.dynamodb.preader.ReadWorker.java

@Override
public void run() {
    while (alive) {
        try {//from  w ww.j a v a  2 s  .  c o  m
            runInternal();
        } catch (InterruptedException e) {
            Thread.interrupted();
        } catch (Throwable e) {
            log.error("Unknown exception thrown!", e);
        }
    }

    log.info("Worker shutting down, no longer alive");
}

From source file:org.Cherry.Modules.Web.Engine.RequestWorker.java

@Override
public void run() {
    log.debug("New connection thread");

    final HttpContext context = new BasicHttpContext(null);

    while (getHttpServerConnection().isOpen()) {
        if (Thread.interrupted())
            throw new IllegalStateException(new InterruptedException());

        try {/*w  ww .  j av  a2s. com*/
            getHttpService().handleRequest(getHttpServerConnection(), context);
        } catch (final ConnectionClosedException err) {
            log.debug("[{}]", err.getMessage());
            break;
        } catch (final Throwable err) {
            log.error(err.getMessage(), err);
            break;
        }
    }

    getMetricsService().examine(getHttpServerConnection());
}

From source file:com.intel.cosbench.driver.operator.Cleaner.java

public static void doDispose(String conName, Config config, Session session) {
    if (Thread.interrupted())
        throw new AbortedException();

    try {/*from ww  w.j  av a  2 s.c o  m*/
        session.getApi().deleteContainer(conName, config);
    } catch (StorageInterruptedException sie) {
        throw new AbortedException();
    } catch (Exception e) {
        doLogErr(session.getLogger(), "fail to perform clean operation", e);
        throw new AgentException(); // mark error
    }

    /* no sample is provided for this operation */
}

From source file:com.siberhus.tdfl.processor.LongRunningDfp.java

@Override
public void validateItem(Employee item, FieldDataException fde) throws Exception {
    if (item.getEmail() == null) {
        fde.addError("email", "missing required field");
    }//w ww  .j  a  va  2s.  c  o m
    if (Thread.interrupted()) {
        //put some cleaning code here
        throw new DataFileLoaderException("STOP");
    }
}

From source file:ru.apertum.qsystem.reports.net.RunnableSocket.java

@Override
public void run() {

    final DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
    try {/*w w w . j  av  a  2s  .  co m*/
        conn.bind(socket, QSystemHtmlInstance.htmlInstance().getParams());
    } catch (IOException ex) {
        throw new ReportException("Not bind socket to connection." + ex);
    }

    final HttpContext context = new BasicHttpContext(null);
    try {
        while (!Thread.interrupted() && conn.isOpen()) {
            QSystemHtmlInstance.htmlInstance().getHttpService().handleRequest(conn, context);
        }
    } catch (ConnectionClosedException ex) {
        QLog.l().logRep().error("Client closed connection", ex);
    } catch (IOException ex) {
        QLog.l().logRep().error("I/O error: " + ex.getMessage(), ex);
    } catch (HttpException ex) {
        QLog.l().logRep().error("Unrecoverable HTTP protocol violation: " + ex.getMessage(), ex);
    } catch (Exception ex) {
        QLog.l().logRep().error("Something with HTTP server.", ex);
    } finally {
        try {
            conn.shutdown();
        } catch (IOException ex) {
            QLog.l().logRep().error("Default Http Server Connection have error then shutdown.", ex);
        } catch (Exception ex) {
            QLog.l().logRep().error("Something with runnableSocket.", ex);
        }
    }

}

From source file:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java

/**
 * Mtodo que extra o contedo de uma pgina web.
 * //from  www. 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:at.alladin.rmbt.android.util.CheckNewsTask.java

@Override
protected void onPostExecute(final JSONArray newsList) {

    if (newsList != null && newsList.length() > 0 && !serverConn.hasError())
        for (int i = 0; i < newsList.length(); i++)
            if (!isCancelled() && !Thread.interrupted())
                try {

                    final JSONObject newsItem = newsList.getJSONObject(i);

                    final DialogFragment newFragment = RMBTAlertDialogFragment.newInstance(
                            newsItem.optString("title", activity.getString(R.string.news_title)),
                            newsItem.optString("text", activity.getString(R.string.news_no_message)), null);

                    newFragment.show(activity.getFragmentManager(), "dialog");

                    if (newsItem.has("uid")) {
                        if (lastNewsUid < newsItem.getLong("uid"))
                            lastNewsUid = newsItem.getLong("uid");
                    }// www  .jav  a  2s  . c  om
                } catch (final JSONException e) {
                    e.printStackTrace();
                }

    ConfigHelper.setLastNewsUid(activity.getApplicationContext(), lastNewsUid);
}

From source file:com.cooksys.httpserver.RequestListenerThread.java

@Override
public void run() {
    System.out.println("Listening on port " + this.serversocket);

    while (!Thread.interrupted()) {
        try {//w w  w  .  j a  va2s .  co  m
            // Listen for connections
            Socket socket = this.serversocket.accept();
            System.out.println("Incoming connection from " + socket.getInetAddress());

            //setup the http connection
            HttpServerConnection conn = this.connFactory.createConnection(socket);

            // Start worker thread
            Thread t = new WorkerThread(this.httpService, conn);
            t.setDaemon(true);
            t.start();
        } catch (InterruptedIOException ex) {
            break;
        } catch (IOException e) {
            System.err.println("Connection interrupted. " + e.getMessage());
            break;
        }
    }

    //clean up socket connection before exiting thread

    System.out.println("Server thread exiting");

}

From source file:org.mule.test.infrastructure.process.CommandServer.java

public void start() throws IOException {
    logger.debug("Trying to create server socket for command service to port: " + serverPort);
    commandSocket = new ServerSocket(serverPort, 0, InetAddress.getByName("localhost"));
    commandServerThread = new Thread("Command-Server") {
        @Override/*from  www  .  jav  a 2 s.c  om*/
        public void run() {
            try {
                Socket processClientConnection = commandSocket.accept();
                BufferedReader processClientLogEntriesInputStream = new BufferedReader(
                        new InputStreamReader(processClientConnection.getInputStream()));
                while (!Thread.interrupted()) {
                    String commandLine = processClientLogEntriesInputStream.readLine();
                    if (commandLine == null) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            return;
                        }
                    } else {
                        logger.info("Command from external process received: " + commandLine);
                        synchronized (this) {
                            if (commandListener == null) {
                                pendingCommands.add(commandLine);
                            } else {
                                commandListener.commandReceived(commandLine);
                            }
                        }
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                closeQuietly(commandSocket);
            }
        }
    };
    commandServerThread.setDaemon(true);
    commandServerThread.start();
}

From source file:gridool.util.net.InterruptableInputStream.java

private int internalRead(final byte[] b, final int off, final int len) throws IOException {
    boolean ntraced = true;
    while (true) {
        try {//from   ww  w  . jav a 2s  .c o  m
            final int n = is.read(b, off, len);
            return n;
        } catch (SocketTimeoutException e) {
            if (Thread.interrupted()) {
                throw e;
            } else {
                Thread thread = Thread.currentThread();
                if (!thread.isDaemon()) {
                    State state = thread.getState();
                    switch (state) {
                    case BLOCKED:
                    case WAITING:
                        if (LOG.isWarnEnabled()) {
                            LOG.warn("thread (" + thread.getName() + "timeout: " + thread.getState(), e);
                        }
                        throw e;
                    default:
                        if (LOG.isTraceEnabled() && ntraced) {
                            ntraced = false;
                            LOG.trace("thread (" + thread.getName() + ") timeout: " + thread.getState());
                        }
                        break;
                    }
                }
            }
        }
    }
}