Example usage for java.util.concurrent Future cancel

List of usage examples for java.util.concurrent Future cancel

Introduction

In this page you can find the example usage for java.util.concurrent Future cancel.

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:com.google.codelabs.migratingtojobs.shared.Downloader.java

/**
 * Stop downloading the provided CatalogItem.
 *//*  w ww  .ja va 2 s .  com*/
private void stop(final CatalogItem item) {
    synchronized (mMap) {
        Future<?> future = mMap.remove(item);
        if (future != null) {
            future.cancel(true);
        }
    }
}

From source file:org.apache.hadoop.hive.ql.io.orc.OrcInputFormat.java

private static void cancelFutures(List<Future<?>> futures) {
    for (Future future : futures) {
        future.cancel(true);
    }/* w ww . j a  va 2 s  . co m*/
}

From source file:com.magnet.plugin.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                }//  w w w .j a  va2  s  . c  om
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new ConnectionException(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:org.silverpeas.core.web.index.IndexationProcessExecutor.java

/**
 * Stops a current indexation operation if it exists a running one.<br>
 * Otherwise, nothing is done./*  w  w  w.ja v  a  2s  . c  o m*/
 */
@SuppressWarnings({ "unchecked", "WeakerAccess", "unused" })
public void stopCurrentExecutionIfAny() {
    final Cache cache = CacheServiceProvider.getApplicationCacheService().getCache();
    Pair<IndexationProcess, Future<Void>> process = cache.get(INDEXATION_PROCESS_EXECUTOR_KEY, Pair.class);
    final Future<Void> task = (process != null) ? process.getRight() : null;
    if (process != null && !task.isDone()) {
        try {
            task.cancel(true);
        } catch (Exception e) {
            SilverLogger.getLogger(this).error("stopping indexation process failed", e);
        }
    }
}

From source file:com.chingo247.structureapi.plan.schematic.SchematicManager.java

private void save(final List<File> schematics) {

    final List<SchematicData> data = new LinkedList<>();
    List<Future> tasks = new LinkedList<>();

    for (final File file : schematics) {
        tasks.add(executor.submit(new Runnable() {

            @Override/*  w  w  w .j  av  a  2s  .  c  om*/
            public void run() {
                try {
                    data.add(SchematicData.load(file));
                } catch (IOException | DataException ex) {
                    Logger.getLogger(SchematicManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }));
    }

    for (Future task : tasks) {
        try {
            task.get();
        } catch (InterruptedException | ExecutionException ex) {
            Logger.getLogger(SchematicManager.class.getName()).log(Level.SEVERE, null, ex);
            for (Future f : tasks) {
                f.cancel(true);
            }
        }
    }

    Session session = null;
    Transaction tx = null;
    try {
        session = HibernateUtil.getSession();
        tx = session.beginTransaction();
        for (SchematicData schematicData : data) {
            session.merge(schematicData);
        }
        tx.commit();
    } catch (HibernateException e) {
        try {
            tx.rollback();
        } catch (HibernateException rbe) {
            Logger.getLogger(AbstractService.class.getName()).log(Level.SEVERE,
                    "Couldnt roll back transaction", rbe);
        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:org.marketcetera.modules.csv.CSVEmitter.java

@Override
public void cancel(DataFlowID inFlowID, RequestID inRequestID) {
    Future<Boolean> future = mRequests.remove(inRequestID);
    if (future != null) {
        future.cancel(true);
    }//  w  w  w.j  a v  a 2 s.co  m
}

From source file:io.hops.resolvingcache.PathMemcache.java

@Override
protected int[] getInternal(final MemcachedClient mc, String path) throws IOException {
    Object ce = null;//from w  w  w.  ja  v  a2 s . c  o m
    Future<Object> f = mc.asyncGet(getKey(path));
    try {
        ce = f.get(1, TimeUnit.SECONDS);
    } catch (Exception ex) {
        LOG.error(ex);
        f.cancel(true);
    }
    if (ce != null && ce instanceof CacheEntry) {
        return ((CacheEntry) ce).getInodeIds();
    }
    return null;
}

From source file:com.magnet.plugin.common.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(CONNECTION_TIMEOUT);
                }//from   ww  w . ja v  a2  s .  c  o m
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new Exception(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:com.splout.db.hadoop.GeneratorCMD.java

public int run(String[] args) throws Exception {
    JCommander jComm = new JCommander(this);
    jComm.setProgramName(/*from   w  ww.j a  v  a 2  s .  c  om*/
            "Splout Tablespaces Generator. Generates tablespaces, ready to be deployed to a Splout Cluster.");
    try {
        jComm.parse(args);
    } catch (Throwable t) {
        t.printStackTrace();
        jComm.usage();
        return -1;
    }

    if (parallelism < 1) {
        System.err.println("Parallelism must be greater than 0.");
        System.exit(1);
    }

    log.info("Parsing input parameters...");

    // All the tablespaces that will be generated and deployed atomically, hashed by their name
    // We generate this first so we can detect errors in the configuration before even using Hadoop
    Map<String, TablespaceSpec> tablespacesToGenerate = new HashMap<String, TablespaceSpec>();

    // Partition maps to reuse at indexation. Used when sampling is skipped.
    final Map<String, PartitionMap> partitionMapsToReuse = new HashMap<String, PartitionMap>();

    for (String tablespaceFile : tablespaceFiles) {
        Path file = new Path(tablespaceFile);
        FileSystem fS = FileSystem.get(file.toUri(), getConf());

        if (!fS.exists(file)) {
            throw new IllegalArgumentException("Config input file: " + file + " doesn't exist!");
        }

        String strContents = HadoopUtils.fileToString(fS, file);
        JSONTablespaceDefinition def = JSONSerDe.deSer(strContents, JSONTablespaceDefinition.class);
        TablespaceSpec spec = def.build(conf);
        String name = def.getName();

        tablespacesToGenerate.put(name, spec);

        // Reusing partition maps?
        if (qnodeURL != null) {
            partitionMapsToReuse.put(name, retrievePartitionMapfromQNode(name));
        }
    }

    if (!FileSystem.getLocal(conf).equals(FileSystem.get(conf))) {
        File nativeLibs = new File("native");
        if (nativeLibs.exists()) {
            SploutHadoopConfiguration.addSQLite4JavaNativeLibsToDC(conf);
        }
    }

    Path out = new Path(output);
    FileSystem outFs = out.getFileSystem(getConf());
    HadoopUtils.deleteIfExists(outFs, out);

    ExecutorService executor = Executors.newFixedThreadPool(parallelism);
    ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(executor);
    ArrayList<Future<Boolean>> generatorFutures = new ArrayList<Future<Boolean>>();

    // Generate each tablespace
    for (final Map.Entry<String, TablespaceSpec> tablespace : tablespacesToGenerate.entrySet()) {
        Path tablespaceOut = new Path(out, tablespace.getKey());
        TablespaceSpec spec = tablespace.getValue();

        log.info("Generating view with Hadoop (" + tablespace.getKey() + ")");
        final TablespaceGenerator viewGenerator = new TablespaceGenerator(spec, tablespaceOut, this.getClass());

        generatorFutures.add(ecs.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                if (qnodeURL == null) {
                    viewGenerator.generateView(conf, samplingType, new TupleSampler.RandomSamplingOptions());
                    return true;
                } else {
                    viewGenerator.generateView(conf, partitionMapsToReuse.get(tablespace.getKey()));
                    return true;
                }
            }
        }));
    }

    // Waiting all tasks to finish.
    for (int i = 0; i < tablespacesToGenerate.size(); i++) {
        // Get will throw an exception if the callable returned it.
        try {
            ecs.take().get();
        } catch (ExecutionException e) {
            // One job was wrong. Stopping the rest.
            for (Future<Boolean> task : generatorFutures) {
                task.cancel(true);
            }
            executor.shutdown();
            throw e;
        }
    }

    executor.shutdown();

    log.info("Done!");
    return 0;
}

From source file:com.ejisto.modules.executor.TaskManager.java

public void cancelTask(String uuid) {
    if (!lock.tryLock()) {
        return;//from   ww w  . j  av a  2s. c o  m
    }
    try {
        TaskEntry entry = registry.get(uuid);
        if (entry == null) {
            return;
        }
        Future<?> future = entry.getFuture();
        if (future != null) {
            future.cancel(true);
        }
    } finally {
        lock.unlock();
    }
}