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.fseek.simon.swing.util.TreeUtil.java

public static void deleteAllChilds(final LinkTreeNode node, final DefaultTreeModel model,
        DefaultMutableTreeNode clearNode) {
    for (int i = 0; i < node.getChildCount(); i++) {
        if (Thread.interrupted()) {
            break;
        }/*w  ww  .  j av a 2s. c o m*/
        final MutableTreeNode childAt = (MutableTreeNode) node.getChildAt(i);
        if (childAt != null && clearNode != null && clearNode != childAt) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    model.removeNodeFromParent(childAt);
                }
            });
        }
    }
}

From source file:io.cloudslang.worker.management.services.InBuffer.java

private void fillBufferPeriodically() {

    while (!inShutdown) {
        try {//from   w w w .  j  a  va  2  s  .c  om
            boolean workerUp = workerManager.isUp();
            if (!workerUp) {
                Thread.sleep(3000); //sleep if worker is not fully started yet
            } else {
                syncManager.startGetMessages(); //we must lock recovery lock before poll - otherwise we will get duplications

                //We need to check if the current thread was interrupted while waiting for the lock (InBufferThread) and RESET its interrupted flag!
                if (Thread.interrupted()) {
                    logger.info(
                            "Thread was interrupted while waiting on the lock in fillBufferPeriodically()!");
                    continue;
                }

                if (needToPoll()) {
                    int messagesToGet = capacity - workerManager.getInBufferSize();

                    if (logger.isDebugEnabled())
                        logger.debug("Polling messages from queue (max " + messagesToGet + ")");
                    List<ExecutionMessage> newMessages = queueDispatcher.poll(workerUuid, messagesToGet);
                    if (executionsActivityListener != null) {
                        executionsActivityListener
                                .onActivate(extract(newMessages, on(ExecutionMessage.class).getExecStateId()));
                    }
                    if (logger.isDebugEnabled())
                        logger.debug("Received " + newMessages.size() + " messages from queue");

                    if (!newMessages.isEmpty()) {
                        //we must acknowledge the messages that we took from the queue
                        ackMessages(newMessages);
                        for (ExecutionMessage msg : newMessages) {
                            addExecutionMessageInner(msg);
                        }

                        syncManager.finishGetMessages(); //release all locks before going to sleep!!!

                        Thread.sleep(coolDownPollingMillis / 8); //cool down - sleep a while
                    } else {
                        syncManager.finishGetMessages(); //release all locks before going to sleep!!!

                        Thread.sleep(coolDownPollingMillis); //if there are no messages - sleep a while
                    }
                } else {
                    syncManager.finishGetMessages(); //release all locks before going to sleep!!!

                    Thread.sleep(coolDownPollingMillis); //if the buffer is not empty enough yet or in recovery - sleep a while
                }
            }
        } catch (InterruptedException ex) {
            logger.error("Fill InBuffer thread was interrupted... ", ex);
            syncManager.finishGetMessages(); //release all locks before going to sleep!!!
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                /*ignore*/}
        } catch (Exception ex) {
            logger.error("Failed to load new ExecutionMessages to the buffer!", ex);
            syncManager.finishGetMessages(); //release all locks before going to sleep!!!
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                /*ignore*/}
        } finally {
            syncManager.finishGetMessages();
        }
    }
}

From source file:net.wimpi.telnetd.util.Mutex.java

public void acquire() throws InterruptedException {
    //log.debug("acquire()::" + Thread.currentThread().toString());
    if (Thread.interrupted())
        throw new InterruptedException();
    synchronized (this) {
        try {//from  w w w.j  a  va  2  s .co m
            while (inuse_)
                wait();
            inuse_ = true;
        } catch (InterruptedException ex) {
            notify();
            throw ex;
        }
    }
}

From source file:org.apache.hadoop.hbase.index.write.TestIndexWriter.java

/**
 * With the move to using a pool of threads to write, we need to ensure that we still block until
 * all index writes for a mutation/batch are completed.
 * @throws Exception on failure/*from  w w w. j  a  v  a 2  s.c o m*/
 */
@SuppressWarnings("unchecked")
@Test
public void testSynchronouslyCompletesAllWrites() throws Exception {
    LOG.info("Starting " + testName.getTableNameString());
    LOG.info("Current thread is interrupted: " + Thread.interrupted());
    Abortable abort = new StubAbortable();
    Stoppable stop = Mockito.mock(Stoppable.class);
    ExecutorService exec = Executors.newFixedThreadPool(1);
    Map<ImmutableBytesPtr, HTableInterface> tables = new HashMap<ImmutableBytesPtr, HTableInterface>();
    FakeTableFactory factory = new FakeTableFactory(tables);

    byte[] tableName = this.testName.getTableName();
    Put m = new Put(row);
    m.add(Bytes.toBytes("family"), Bytes.toBytes("qual"), null);
    Collection<Pair<Mutation, byte[]>> indexUpdates = Arrays.asList(new Pair<Mutation, byte[]>(m, tableName));

    HTableInterface table = Mockito.mock(HTableInterface.class);
    final boolean[] completed = new boolean[] { false };
    Mockito.when(table.batch(Mockito.anyList())).thenAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // just keep track that it was called
            completed[0] = true;
            return null;
        }
    });
    Mockito.when(table.getTableName()).thenReturn(testName.getTableName());
    // add the table to the set of tables, so its returned to the writer
    tables.put(new ImmutableBytesPtr(tableName), table);

    // setup the writer and failure policy
    ParallelWriterIndexCommitter committer = new ParallelWriterIndexCommitter();
    committer.setup(factory, exec, abort, stop, 2);
    KillServerOnFailurePolicy policy = new KillServerOnFailurePolicy();
    policy.setup(stop, abort);
    IndexWriter writer = new IndexWriter(committer, policy);
    writer.write(indexUpdates);
    assertTrue("Writer returned before the table batch completed! Likely a race condition tripped",
            completed[0]);
    writer.stop(this.testName.getTableNameString() + " finished");
    assertTrue("Factory didn't get shutdown after writer#stop!", factory.shutdown);
    assertTrue("ExectorService isn't terminated after writer#stop!", exec.isShutdown());
}

From source file:org.apache.phoenix.hbase.index.write.TestIndexWriter.java

/**
 * With the move to using a pool of threads to write, we need to ensure that we still block until
 * all index writes for a mutation/batch are completed.
 * @throws Exception on failure// w  w  w .java  2  s .  c  o m
 */
@SuppressWarnings({ "unchecked", "deprecation" })
@Test
public void testSynchronouslyCompletesAllWrites() throws Exception {
    LOG.info("Starting " + testName.getTableNameString());
    LOG.info("Current thread is interrupted: " + Thread.interrupted());
    Abortable abort = new StubAbortable();
    Stoppable stop = Mockito.mock(Stoppable.class);
    ExecutorService exec = Executors.newFixedThreadPool(1);
    Map<ImmutableBytesPtr, HTableInterface> tables = new HashMap<ImmutableBytesPtr, HTableInterface>();
    FakeTableFactory factory = new FakeTableFactory(tables);

    byte[] tableName = this.testName.getTableName();
    Put m = new Put(row);
    m.add(Bytes.toBytes("family"), Bytes.toBytes("qual"), null);
    Collection<Pair<Mutation, byte[]>> indexUpdates = Arrays.asList(new Pair<Mutation, byte[]>(m, tableName));

    HTableInterface table = Mockito.mock(HTableInterface.class);
    final boolean[] completed = new boolean[] { false };
    Mockito.when(table.batch(Mockito.anyList())).thenAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // just keep track that it was called
            completed[0] = true;
            return null;
        }
    });
    Mockito.when(table.getTableName()).thenReturn(testName.getTableName());
    // add the table to the set of tables, so its returned to the writer
    tables.put(new ImmutableBytesPtr(tableName), table);

    // setup the writer and failure policy
    ParallelWriterIndexCommitter committer = new ParallelWriterIndexCommitter(VersionInfo.getVersion());
    committer.setup(factory, exec, abort, stop, 2);
    KillServerOnFailurePolicy policy = new KillServerOnFailurePolicy();
    policy.setup(stop, abort);
    IndexWriter writer = new IndexWriter(committer, policy);
    writer.write(indexUpdates);
    assertTrue("Writer returned before the table batch completed! Likely a race condition tripped",
            completed[0]);
    writer.stop(this.testName.getTableNameString() + " finished");
    assertTrue("Factory didn't get shutdown after writer#stop!", factory.shutdown);
    assertTrue("ExectorService isn't terminated after writer#stop!", exec.isShutdown());
}

From source file:org.devtcg.five.server.AbstractHttpServer.java

public void run() {
    if (mReqHandler == null)
        throw new IllegalStateException("Request handler not set.");

    while (Thread.interrupted() == false) {
        try {/* w w w.j  a v  a  2  s  .  c  o  m*/
            Socket sock = getSocket().accept();
            DefaultHttpServerConnection conn = new DefaultHttpServerConnection();

            conn.bind(sock, mParams);

            BasicHttpProcessor proc = new BasicHttpProcessor();
            proc.addInterceptor(new ResponseContent());
            proc.addInterceptor(new ResponseConnControl());

            HttpRequestHandlerRegistry reg = new HttpRequestHandlerRegistry();
            reg.register("*", mReqHandler);

            HttpService svc = new HttpService(proc, new DefaultConnectionReuseStrategy(),
                    new DefaultHttpResponseFactory());

            svc.setParams(mParams);
            svc.setHandlerResolver(reg);

            WorkerThread t;

            synchronized (mWorkers) {
                t = new WorkerThread(svc, conn);
                mWorkers.add(t);
            }

            t.start();
        } catch (IOException e) {
            if (!hasCanceled()) {
                if (LOG.isErrorEnabled())
                    LOG.error("I/O error initializing connection thread", e);
            }
            break;
        }
    }
}

From source file:com.facebook.stetho.server.LocalSocketHttpServer.java

private void listenOnAddress(String address) throws IOException {
    mServerSocket = bindToSocket(address);
    LogUtil.i("Listening on @" + address);

    HttpParams params = null;/*from  www .j  a va 2  s  . c om*/
    HttpService service = null;

    while (!Thread.interrupted()) {
        LocalSocketHttpServerConnection connection = new LocalSocketHttpServerConnection();
        try {
            // Use previously accepted socket the first time around, otherwise wait to
            // accept another.
            LocalSocket socket = mServerSocket.accept();

            if (params == null) {
                params = createParams();
            }
            if (service == null) {
                service = createService(params);
            }
            connection.bind(socket, params);

            // Start worker thread
            Thread t = new WorkerThread(service, connection);
            t.setDaemon(true);
            t.start();
        } catch (SocketException se) {
            // ignore exception if interrupting the thread
            if (!Thread.interrupted()) {
                LogUtil.w(se, "I/O error");
            }
        } catch (InterruptedIOException ex) {
            break;
        } catch (IOException e) {
            LogUtil.w(e, "I/O error initialising connection thread");
            break;
        }
    }
}

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

public static Sample doWrite(InputStream in, long length, String conName, String objName, Config config,
        Session session) {/*from  ww w .java2  s  .c  o m*/
    if (Thread.interrupted())
        throw new AbortedException();

    CountingInputStream cin = new CountingInputStream(in);

    long start = System.currentTimeMillis();

    try {
        session.getApi().createObject(conName, objName, cin, length, config);
    } catch (StorageInterruptedException sie) {
        throw new AbortedException();
    } catch (Exception e) {
        session.getLogger().error("fail to perform write operation", e);
        return new Sample(new Date(), OP_TYPE, false);
    } finally {
        IOUtils.closeQuietly(cin);
    }

    long end = System.currentTimeMillis();

    Date now = new Date(end);
    return new Sample(now, OP_TYPE, true, end - start, cin.getByteCount());
}

From source file:net.femtoparsec.jnlmin.AbstractTokenTask.java

protected boolean isRunning() {
    return this.statusManager.getStatus() == MinimizerStatus.RUNNING && !Thread.interrupted();
}