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:com.splout.db.dnode.DNodeHandler.java

/**
 * Runs a deploy action. Downloads file and warm up the data.
 * Interruptible./*from   w w w .  jav  a  2  s . co  m*/
 */
private void runDeployAction(Fetcher.Reporter reporter, DeployAction action, long version)
        throws IOException, URISyntaxException, DNodeException, InterruptedException {

    log.info("Running deployAction[" + action + "] for version[" + version + "].");
    // 1- Call the fetcher for fetching
    File fetchedContent = fetcher.fetch(action.getDataURI(), reporter);
    // If we reach this point then the fetch has been OK
    // 2- Create the local folder were to move the fetched data
    File dbFolder = getLocalStorageFolder(action.getTablespace(), action.getPartition(), version);
    if (dbFolder.exists()) { // If the new folder where we want to deploy
        // already exists means it is
        // somehow
        // stalled from a previous failed deploy - it is ok to delete it
        FileUtils.deleteDirectory(dbFolder);
    }
    // 3- Perform a "mv" for finally making the data available
    FileUtils.moveDirectory(fetchedContent, dbFolder);

    // 4- Check if interrupted. In this case, we remove the folder before returning
    if (Thread.interrupted()) {
        try {
            FileUtils.deleteDirectory(dbFolder);
        } catch (IOException e) {
            log.warn("Not possible to remove " + dbFolder + " when trying to cancel de deployment.");
        }
        throw new InterruptedException();
    }

    // 5- Store metadata about the partition
    writePartitionMetadata(action, version);

    // 6- Preemptively load the Manager in case initialization is slow
    // Managers might warm up for a while (e.g. loading data into memory)
    loadManagerInEHCache(action.getTablespace(), action.getVersion(), action.getPartition(), dbFolder,
            action.getMetadata());
    log.info("Finished deployAction[" + action + "] for version[" + version + "].");
}

From source file:com.omertron.yamjtrakttv.view.MainWindow.java

private void btnProgressOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProgressOKActionPerformed
    updateButtons();//from  w  w  w .jav a2s.c o  m
    fraProgress.setVisible(Boolean.FALSE);
    Thread.interrupted();
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Verifies the code and media resources associated with this application. A list of resources
 * that do not exist or fail the verification process will be returned. If all resources are
 * ready to go, null will be returned and the application is considered ready to run.
 *
 * @param obs a progress observer that will be notified of verification progress. NOTE: this
 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
 * you have to take care to get back to your UI thread.
 * @param alreadyValid if non-null a 1 element array that will have the number of "already
 * validated" resources filled in./*from w ww  .  j ava  2s.c o m*/
 * @param unpacked a set to populate with unpacked resources.
 */
public List<Resource> verifyResources(ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked)
        throws InterruptedException {
    List<Resource> rsrcs = getAllActiveResources();
    List<Resource> failures = new ArrayList<Resource>();

    // obtain the sizes of the resources to validate
    long[] sizes = new long[rsrcs.size()];
    for (int ii = 0; ii < sizes.length; ii++) {
        sizes[ii] = rsrcs.get(ii).getLocal().length();
    }

    ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
    boolean noUnpack = SysProps.noUnpack();
    for (int ii = 0; ii < sizes.length; ii++) {
        Resource rsrc = rsrcs.get(ii);
        if (Thread.interrupted()) {
            throw new InterruptedException("m.applet_stopped");
        }

        ProgressObserver robs = pagg.startElement(ii);
        if (rsrc.isMarkedValid()) {
            if (alreadyValid != null) {
                alreadyValid[0]++;
            }
            robs.progress(100);
            continue;
        }

        try {
            if (_digest.validateResource(rsrc, robs)) {
                // unpack this resource if appropriate
                if (noUnpack || !rsrc.shouldUnpack()) {
                    // finally note that this resource is kosher
                    rsrc.markAsValid();
                    continue;
                }
                if (rsrc.unpack()) {
                    unpacked.add(rsrc);
                    rsrc.markAsValid();
                    continue;
                }
                log.info("Failure unpacking resource", "rsrc", rsrc);
            }

        } catch (Exception e) {
            log.info("Failure validating resource. Requesting redownload...", "rsrc", rsrc, "error", e);

        } finally {
            robs.progress(100);
        }
        failures.add(rsrc);
    }

    return (failures.size() == 0) ? null : failures;
}

From source file:org.apache.hadoop.hbase.client.TestHCM.java

/**
 * Tests that a destroyed connection does not have a live zookeeper.
 * Below is timing based.  We put up a connection to a table and then close the connection while
 * having a background thread running that is forcing close of the connection to try and
 * provoke a close catastrophe; we are hoping for a car crash so we can see if we are leaking
 * zk connections./*from   w w w.  ja v  a 2  s . c  o m*/
 * @throws Exception
 */
@Ignore("Flakey test: See HBASE-8996")
@Test
public void testDeleteForZKConnLeak() throws Exception {
    TEST_UTIL.createTable(TABLE_NAME4, FAM_NAM);
    final Configuration config = HBaseConfiguration.create(TEST_UTIL.getConfiguration());
    config.setInt("zookeeper.recovery.retry", 1);
    config.setInt("zookeeper.recovery.retry.intervalmill", 1000);
    config.setInt("hbase.rpc.timeout", 2000);
    config.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);

    ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 10, 5, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), Threads.newDaemonThreadFactory("test-hcm-delete"));

    pool.submit(new Runnable() {
        @Override
        public void run() {
            while (!Thread.interrupted()) {
                try {
                    HConnection conn = HConnectionManager.getConnection(config);
                    LOG.info("Connection " + conn);
                    HConnectionManager.deleteStaleConnection(conn);
                    LOG.info("Connection closed " + conn);
                    // TODO: This sleep time should be less than the time that it takes to open and close
                    // a table.  Ideally we would do a few runs first to measure.  For now this is
                    // timing based; hopefully we hit the bad condition.
                    Threads.sleep(10);
                } catch (Exception e) {
                }
            }
        }
    });

    // Use connection multiple times.
    for (int i = 0; i < 30; i++) {
        HConnection c1 = null;
        try {
            c1 = ConnectionManager.getConnectionInternal(config);
            LOG.info("HTable connection " + i + " " + c1);
            HTable table = new HTable(config, TABLE_NAME4, pool);
            table.close();
            LOG.info("HTable connection " + i + " closed " + c1);
        } catch (Exception e) {
            LOG.info("We actually want this to happen!!!!  So we can see if we are leaking zk", e);
        } finally {
            if (c1 != null) {
                if (c1.isClosed()) {
                    // cannot use getZooKeeper as method instantiates watcher if null
                    Field zkwField = c1.getClass().getDeclaredField("keepAliveZookeeper");
                    zkwField.setAccessible(true);
                    Object watcher = zkwField.get(c1);

                    if (watcher != null) {
                        if (((ZooKeeperWatcher) watcher).getRecoverableZooKeeper().getState().isAlive()) {
                            // non-synchronized access to watcher; sleep and check again in case zk connection
                            // hasn't been cleaned up yet.
                            Thread.sleep(1000);
                            if (((ZooKeeperWatcher) watcher).getRecoverableZooKeeper().getState().isAlive()) {
                                pool.shutdownNow();
                                fail("Live zookeeper in closed connection");
                            }
                        }
                    }
                }
                c1.close();
            }
        }
    }
    pool.shutdownNow();
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Unpacks the resources that require it (we know that they're valid).
 *
 * @param unpacked a set of resources to skip because they're already unpacked.
 *//*from   www.j  a  v a 2 s  .  com*/
public void unpackResources(ProgressObserver obs, Set<Resource> unpacked) throws InterruptedException {
    List<Resource> rsrcs = getActiveResources();

    // remove resources that we don't want to unpack
    for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext();) {
        Resource rsrc = it.next();
        if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
            it.remove();
        }
    }

    // obtain the sizes of the resources to unpack
    long[] sizes = new long[rsrcs.size()];
    for (int ii = 0; ii < sizes.length; ii++) {
        sizes[ii] = rsrcs.get(ii).getLocal().length();
    }

    ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
    for (int ii = 0; ii < sizes.length; ii++) {
        if (Thread.interrupted()) {
            throw new InterruptedException("m.applet_stopped");
        }
        Resource rsrc = rsrcs.get(ii);
        ProgressObserver pobs = pagg.startElement(ii);
        if (!rsrc.unpack()) {
            log.info("Failure unpacking resource", "rsrc", rsrc);
        }
        pobs.progress(100);
    }
}

From source file:com.datatorrent.stram.cli.DTCli.java

private void processLine(String line, final ConsoleReader reader, boolean expandMacroAlias) {
    try {//from   w w w .  j  av  a 2s  .co m
        // clear interrupt flag
        Thread.interrupted();
        if (reader.isHistoryEnabled()) {
            History history = reader.getHistory();
            if (history instanceof FileHistory) {
                try {
                    ((FileHistory) history).flush();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
        //LOG.debug("line: \"{}\"", line);
        List<String[]> commands = tokenizer.tokenize(line);
        if (commands == null) {
            return;
        }
        for (final String[] args : commands) {
            if (args.length == 0 || StringUtils.isBlank(args[0])) {
                continue;
            }
            //LOG.debug("Got: {}", mapper.writeValueAsString(args));
            if (expandMacroAlias) {
                if (macros.containsKey(args[0])) {
                    List<String> macroItems = expandMacro(macros.get(args[0]), args);
                    for (String macroItem : macroItems) {
                        if (consolePresent) {
                            System.out.println("expanded-macro> " + macroItem);
                        }
                        processLine(macroItem, reader, false);
                    }
                    continue;
                }

                if (aliases.containsKey(args[0])) {
                    processLine(aliases.get(args[0]), reader, false);
                    continue;
                }
            }
            CommandSpec cs = null;
            if (changingLogicalPlan) {
                cs = logicalPlanChangeCommands.get(args[0]);
            } else {
                if (currentApp != null) {
                    cs = connectedCommands.get(args[0]);
                }
                if (cs == null) {
                    cs = globalCommands.get(args[0]);
                }
            }
            if (cs == null) {
                if (connectedCommands.get(args[0]) != null) {
                    System.err.println("\"" + args[0]
                            + "\" is valid only when connected to an application. Type \"connect <appid>\" to connect to an application.");
                    lastCommandError = true;
                } else if (logicalPlanChangeCommands.get(args[0]) != null) {
                    System.err.println("\"" + args[0]
                            + "\" is valid only when changing a logical plan.  Type \"begin-logical-plan-change\" to change a logical plan");
                    lastCommandError = true;
                } else {
                    System.err.println("Invalid command '" + args[0] + "'. Type \"help\" for list of commands");
                    lastCommandError = true;
                }
            } else {
                try {
                    cs.verifyArguments(args);
                } catch (CliException ex) {
                    cs.printUsage(args[0]);
                    throw ex;
                }
                final Command command = cs.command;
                commandThread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            command.execute(args, reader);
                            lastCommandError = false;
                        } catch (Exception e) {
                            handleException(e);
                        } catch (Error e) {
                            handleException(e);
                            System.err.println("Fatal error encountered");
                            System.exit(1);
                        }
                    }

                };
                mainThread = Thread.currentThread();
                commandThread.start();
                try {
                    commandThread.join();
                } catch (InterruptedException ex) {
                    System.err.println("Interrupted");
                }
                commandThread = null;
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImpl.java

/**
 * Complete the block write!/*from   w w  w. j  av  a 2 s . co m*/
 */
@Override // FsDatasetSpi
public synchronized void finalizeBlock(ExtendedBlock b) throws IOException {
    if (Thread.interrupted()) {
        // Don't allow data modifications from interrupted threads
        throw new IOException("Cannot finalize block from Interrupted Thread");
    }
    ReplicaInfo replicaInfo = getReplicaInfo(b);
    if (replicaInfo.getState() == ReplicaState.FINALIZED) {
        // this is legal, when recovery happens on a file that has
        // been opened for append but never modified
        return;
    }
    finalizeReplica(b.getBlockPoolId(), replicaInfo);
}

From source file:org.kchine.rpf.PoolUtils.java

public static void callBack(final ServantCreationListener servantCreationListener, final ManagedServant servant,
        final RemoteException exception) {
    try {// w  ww  . j av a  2 s.  com

        final Object[] resultHolder = new Object[1];
        Runnable setServantStubRunnable = new Runnable() {
            public void run() {
                try {
                    if (servant != null) {
                        servantCreationListener.setServantStub(servant);
                    } else {
                        servantCreationListener.setRemoteException(exception);
                    }
                    resultHolder[0] = PoolUtils.SET_SERVANT_STUB_DONE;
                } catch (Exception e) {
                    final boolean wasInterrupted = Thread.interrupted();
                    if (wasInterrupted) {
                        resultHolder[0] = new RmiCallInterrupted();
                    } else {
                        resultHolder[0] = e;
                    }
                }
            }
        };

        Thread setServantStubThread = InterruptibleRMIThreadFactory.getInstance()
                .newThread(setServantStubRunnable);
        setServantStubThread.start();

        long t1 = System.currentTimeMillis();
        while (resultHolder[0] == null) {
            if ((System.currentTimeMillis() - t1) > PoolUtils.SET_SERVANT_STUB_TIMEOUT_MILLISEC) {
                setServantStubThread.interrupt();
                resultHolder[0] = new RmiCallTimeout();
                break;
            }
            try {
                Thread.sleep(10);
            } catch (Exception e) {
            }
        }

        if (resultHolder[0] instanceof Throwable) {
            throw (RemoteException) resultHolder[0];
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.datatorrent.stram.cli.ApexCli.java

protected void processLine(String line, final ConsoleReader reader, boolean expandMacroAlias) {
    try {/*from   w  w  w.  j a  v a2 s.com*/
        // clear interrupt flag
        Thread.interrupted();
        if (reader.isHistoryEnabled()) {
            History history = reader.getHistory();
            if (history instanceof FileHistory) {
                try {
                    ((FileHistory) history).flush();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
        //LOG.debug("line: \"{}\"", line);
        List<String[]> commands = tokenizer.tokenize(line);
        if (commands == null) {
            return;
        }
        for (final String[] args : commands) {
            if (args.length == 0 || StringUtils.isBlank(args[0])) {
                continue;
            }
            //LOG.debug("Got: {}", mapper.writeValueAsString(args));
            if (expandMacroAlias) {
                if (macros.containsKey(args[0])) {
                    List<String> macroItems = expandMacro(macros.get(args[0]), args);
                    for (String macroItem : macroItems) {
                        if (consolePresent) {
                            System.out.println("expanded-macro> " + macroItem);
                        }
                        processLine(macroItem, reader, false);
                    }
                    continue;
                }

                if (aliases.containsKey(args[0])) {
                    processLine(aliases.get(args[0]), reader, false);
                    continue;
                }
            }
            CommandSpec cs = null;
            if (changingLogicalPlan) {
                cs = logicalPlanChangeCommands.get(args[0]);
            } else {
                if (currentApp != null) {
                    cs = connectedCommands.get(args[0]);
                }
                if (cs == null) {
                    cs = globalCommands.get(args[0]);
                }
            }
            if (cs == null) {
                if (connectedCommands.get(args[0]) != null) {
                    System.err.println("\"" + args[0]
                            + "\" is valid only when connected to an application. Type \"connect <appid>\" to connect to an application.");
                    lastCommandError = true;
                } else if (logicalPlanChangeCommands.get(args[0]) != null) {
                    System.err.println("\"" + args[0]
                            + "\" is valid only when changing a logical plan.  Type \"begin-logical-plan-change\" to change a logical plan");
                    lastCommandError = true;
                } else {
                    System.err.println("Invalid command '" + args[0] + "'. Type \"help\" for list of commands");
                    lastCommandError = true;
                }
            } else {
                try {
                    cs.verifyArguments(args);
                } catch (CliException ex) {
                    cs.printUsage(args[0]);
                    throw ex;
                }
                final Command command = cs.command;
                commandThread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            command.execute(args, reader);
                            lastCommandError = false;
                        } catch (Exception e) {
                            handleException(e);
                        } catch (Error e) {
                            handleException(e);
                            System.err.println("Fatal error encountered");
                            System.exit(1);
                        }
                    }

                };
                mainThread = Thread.currentThread();
                commandThread.start();
                try {
                    commandThread.join();
                } catch (InterruptedException ex) {
                    System.err.println("Interrupted");
                }
                commandThread = null;
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}