Example usage for java.util.concurrent Future isCancelled

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

Introduction

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

Prototype

boolean isCancelled();

Source Link

Document

Returns true if this task was cancelled before it completed normally.

Usage

From source file:info.magnolia.imaging.caching.CachingImageStreamerRepositoryTest.java

/**
 * This test is not executed by default - too long !
 * Used to reproduce the "session already closed issue", see MGNLIMG-59.
 * Set the "expiration" property of the jobs map in CachingImageStreamer to a longer value
 * to have more chances of reproducing the problem.
 *///from  ww w .  j  av  a 2s.c om
@Ignore
@Test
public void testConcurrencyAndJCRSessions() throws Exception {
    final HierarchyManager srcHM = MgnlContext.getHierarchyManager("website");
    final String srcPath = "/foo/bar";
    ContentUtil.createPath(srcHM, srcPath);

    // ParameterProvider for tests - return a new instance of the same node everytime
    // if we'd return the same src instance everytime, the purpose of this test would be null
    final ParameterProviderFactory<Object, Content> ppf = new TestParameterProviderFactory(srcHM, srcPath);

    final OutputFormat png = new OutputFormat();
    png.setFormatName("png");

    final ImageOperationChain<ParameterProvider<Content>> generator = new ImageOperationChain<ParameterProvider<Content>>();
    final URLImageLoader<ParameterProvider<Content>> load = new URLImageLoader<ParameterProvider<Content>>();
    load.setUrl(getClass().getResource("/funnel.gif").toExternalForm());
    generator.addOperation(load);
    generator.setOutputFormat(png);
    generator.setName("foo blob bar");
    generator.setParameterProviderFactory(ppf);

    // yeah, we're using a "wrong" workspace for the image cache, to avoid having to setup a custom one in this test
    final HierarchyManager hm = MgnlContext.getHierarchyManager("config");

    final ImageStreamer streamer = new CachingImageStreamer(hm, ppf.getCachingStrategy(),
            new DefaultImageStreamer());

    // thread pool of 10, launching 8 requests, can we hit some concurrency please ?
    final ExecutorService executor = Executors.newFixedThreadPool(10);
    final ByteArrayOutputStream[] outs = new ByteArrayOutputStream[8];
    final Future[] futures = new Future[8];
    for (int i = 0; i < outs.length; i++) {
        final int ii = i;
        outs[i] = new ByteArrayOutputStream();
        futures[i] = executor.submit(new Runnable() {
            @Override
            public void run() {
                final ParameterProvider p = generator.getParameterProviderFactory()
                        .newParameterProviderFor(null);
                try {
                    streamer.serveImage(generator, p, outs[ii]);
                } catch (Exception e) {
                    throw new RuntimeException(e); // TODO
                }
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(30, TimeUnit.SECONDS);

    for (Future<?> future : futures) {
        assertTrue(future.isDone());
        assertFalse(future.isCancelled());
        // ignore the results of TestJob - but if there was an exception thrown by TestJob.call(),
        // it is only thrown back at us when we call get() below. (so the test will fail badly if the job threw an exception)
        Object ignored = future.get();
    }

    shutdownRepository(true);

    // sleep for a while so that the jobs map's expiration thread can kick in !
    Thread.sleep(10000);
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

public <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request, true);

    CloseableHttpAsyncClient asyncHttpClient = options.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();//from   ww  w  .  j  a v a 2 s  .  c  o m
        AsyncIdleConnectionMonitorThread asyncIdleConnectionMonitorThread = (AsyncIdleConnectionMonitorThread) options
                .getOption(Option.ASYNC_MONITOR);
        asyncIdleConnectionMonitorThread.start();
    }

    final Future<org.apache.http.HttpResponse> future = asyncHttpClient.execute(requestObj,
            prepareCallback(responseClass, callback));

    return new Future<HttpResponse<T>>() {

        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        public boolean isCancelled() {
            return future.isCancelled();
        }

        public boolean isDone() {
            return future.isDone();
        }

        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }

        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout, unit);
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }
    };
}

From source file:org.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrServer.java

private RequestTaskState getResponseIfReady(ExecutorCompletionService<RequestTaskState> executer,
        boolean waitUntilTaskComplete) throws SolrException {

    Future<RequestTaskState> taskInProgress = null;
    try {/*from  w  w w. ja va2 s.  c om*/
        if (waitUntilTaskComplete) {
            taskInProgress = executer.take();
        } else {
            taskInProgress = executer.poll(backUpRequestDelay, TimeUnit.MILLISECONDS);
        }
        // could be null if poll time exceeded in which case return null.
        if (taskInProgress != null && !taskInProgress.isCancelled()) {
            RequestTaskState resp = taskInProgress.get();
            return resp;
        }
    } catch (InterruptedException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    } catch (ExecutionException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    }
    return null;
}

From source file:info.magnolia.imaging.caching.CachingImageStreamerRepositoryTest.java

@Test
public void testRequestForSimilarUncachedImageOnlyGeneratesItOnce() throws Exception {
    final HierarchyManager srcHM = MgnlContext.getHierarchyManager("website");
    final String srcPath = "/foo/bar";
    ContentUtil.createPath(srcHM, srcPath);

    // ParameterProvider for tests - return a new instance of the same node everytime
    // if we'd return the same src instance everytime, the purpose of this test would be null
    final ParameterProviderFactory<Object, Content> ppf = new TestParameterProviderFactory(srcHM, srcPath);

    final OutputFormat png = new OutputFormat();
    png.setFormatName("png");

    final BufferedImage dummyImg = ImageIO.read(getClass().getResourceAsStream("/funnel.gif"));
    assertNotNull("Couldn't load dummy test image", dummyImg);

    final ImageGenerator<ParameterProvider<Content>> generator = mock(ImageGenerator.class);
    when(generator.getParameterProviderFactory()).thenReturn(ppf);
    when(generator.getName()).thenReturn("test");
    when(generator.getOutputFormat(isA(ParameterProvider.class))).thenReturn(png);

    // aaaaand finally, here's the real reason for this test !
    when(generator.generate(isA(ParameterProvider.class))).thenReturn(dummyImg);

    // yeah, we're using a "wrong" workspace for the image cache, to avoid having to setup a custom one in this test
    final HierarchyManager hm = MgnlContext.getHierarchyManager("config");
    final ImageStreamer streamer = new CachingImageStreamer(hm, ppf.getCachingStrategy(),
            new DefaultImageStreamer());

    // Generator instances will always be the same (including paramProvFac)
    // since they are instantiated with the module config and c2b.
    // ParamProv is a new instance every time.
    // streamer can (must) be the same - once single HM, one cache.

    // thread pool of 10, launching 8 requests, can we hit some concurrency please ?
    final ExecutorService executor = Executors.newFixedThreadPool(10);
    final ByteArrayOutputStream[] outs = new ByteArrayOutputStream[8];
    final Future[] futures = new Future[8];
    for (int i = 0; i < outs.length; i++) {
        outs[i] = new ByteArrayOutputStream();
        futures[i] = executor.submit(new TestJob(generator, streamer, outs[i]));
    }/*from w w  w .ja  va 2s .  c  om*/
    executor.shutdown();
    executor.awaitTermination(30, TimeUnit.SECONDS);

    for (Future<?> future : futures) {
        assertTrue(future.isDone());
        assertFalse(future.isCancelled());
        // ignore the results of TestJob - all we care about is if an exception was thrown
        // and if there was any, it is kept in Future until we call Future.get()
        future.get();
    }

    final NodeData cachedNodeData = hm.getNodeData("/test/website/foo/bar/generated-image");
    // update node meta data
    Content cachedNode = hm.getContent("/test/website/foo/bar");
    cachedNode.getMetaData().setModificationDate();
    cachedNode.save();
    final InputStream res = cachedNodeData.getStream();
    final ByteArrayOutputStream cachedOut = new ByteArrayOutputStream();
    IOUtils.copy(res, cachedOut);

    // assert all outs are the same
    for (int i = 1; i < outs.length; i++) {
        // TODO assert they're all equals byte to byte to the source? or in size? can't as-is since we convert...
        final byte[] a = outs[i - 1].toByteArray();
        final byte[] b = outs[i].toByteArray();
        assertTrue(a.length > 0);
        assertEquals("Different sizes (" + Math.abs(a.length - b.length) + " bytes diff.) with i=" + i,
                a.length, b.length);
        assertTrue("not equals for outs/" + i, Arrays.equals(a, b));
        outs[i - 1] = null; // cleanup all those byte[], or we'll soon run out of memory
    }
    assertTrue("failed comparing last thread's result with what we got from hierarchyManager",
            Arrays.equals(outs[outs.length - 1].toByteArray(), cachedOut.toByteArray()));
    outs[outs.length - 1] = null;

    // now start again another bunch of requests... they should ALL get their results from the cache
    final ExecutorService executor2 = Executors.newFixedThreadPool(10);
    final ByteArrayOutputStream[] outs2 = new ByteArrayOutputStream[8];
    final Future[] futures2 = new Future[8];
    for (int i = 0; i < outs2.length; i++) {
        outs2[i] = new ByteArrayOutputStream();
        futures2[i] = executor2.submit(new TestJob(generator, streamer, outs2[i]));
    }
    executor2.shutdown();
    executor2.awaitTermination(30, TimeUnit.SECONDS);

    for (Future<?> future : futures2) {
        assertTrue(future.isDone());
        assertFalse(future.isCancelled());
        // ignore the results of TestJob - all we care about is if an exception was thrown
        // and if there was any, it is kept in Future until we call Future.get()
        future.get();
    }

    final NodeData cachedNodeData2 = hm.getNodeData("/test/website/foo/bar/generated-image");
    final InputStream res2 = cachedNodeData2.getStream();
    final ByteArrayOutputStream cachedOut2 = new ByteArrayOutputStream();
    IOUtils.copy(res2, cachedOut2);

    // assert all outs are the same
    for (int i = 1; i < outs2.length; i++) {
        // TODO assert they're all equals byte to byte to the source? or in size? can't as-is since we re-save..
        final byte[] a = outs2[i - 1].toByteArray();
        final byte[] b = outs2[i].toByteArray();
        assertTrue(a.length > 0);
        assertEquals("Different sizes (" + Math.abs(a.length - b.length) + " bytes diff.) with i=" + i,
                a.length, b.length);
        assertTrue("not equals for outs2/" + i, Arrays.equals(a, b));
        outs2[i - 1] = null;
    }
    assertTrue("failed comparing last thread's result with what we got from hierarchyManager",
            Arrays.equals(outs2[outs2.length - 1].toByteArray(), cachedOut2.toByteArray()));

    outs2[outs2.length - 1] = null;
}

From source file:com.epam.reportportal.apache.http.impl.conn.PoolingHttpClientConnectionManager.java

protected HttpClientConnection leaseConnection(final Future<CPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
    final CPoolEntry entry;
    try {//ww  w.  j a  va 2s.  c  om
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return CPoolProxy.newProxy(entry);
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}

From source file:org.trend.hgraph.util.test.HGraphClientPerformanceTest.java

@Override
public int run(String[] args) throws Exception {
    if (null == args || args.length < 4) {
        System.err.println("Options must greater than 4");
        printUsage();/* w  ww  .  j a  v  a 2s  .  c  om*/
        return -1;
    }

    System.out.println("args=" + Arrays.toString(args));
    String cmd = null;
    int mustStartIdx = -1;
    int level = 2;
    int threads = 100;
    long interval = 1000; // ms
    boolean isMs = false;
    for (int a = 0; a < args.length; a++) {
        cmd = args[a];
        if (cmd.startsWith("-")) {
            if (mustStartIdx != -1) {
                System.err.println("must start option order is incorrect");
                printUsage();
                return -1;
            }

            if ("-l".equals(cmd)) {
                a++;
                cmd = args[a];
                try {
                    level = Integer.parseInt(cmd);
                } catch (NumberFormatException e) {
                    System.err.println("parse number for -l:" + cmd + " failed");
                    printUsage();
                    return -1;
                }
            } else if ("-t".equals(cmd)) {
                a++;
                cmd = args[a];
                try {
                    threads = Integer.parseInt(cmd);
                } catch (NumberFormatException e) {
                    System.err.println("parse number for -t:" + cmd + " failed");
                    printUsage();
                    return -1;
                }
            } else if ("-m".equals(cmd)) {
                isMs = true;
            } else if ("-i".equals(cmd)) {
                a++;
                cmd = args[a];
                try {
                    interval = Long.parseLong(cmd);
                } catch (NumberFormatException e) {
                    System.err.println("parse number for -i:" + cmd + " failed");
                    printUsage();
                    return -1;
                }

            } else {
                System.err.println("undefined option:" + cmd);
                printUsage();
                return -1;
            }

        } else {
            if (mustStartIdx == -1) {
                mustStartIdx = a;
                break;
            } else {
                System.err.println("must start option order is incorrect");
                printUsage();
                return -1;
            }
        }
    }

    if (mustStartIdx + 4 != args.length) {
        System.err.println("The must option still not satisfied !!");
        printUsage();
        return -1;
    }

    String vt = args[mustStartIdx];
    String et = args[mustStartIdx + 1];
    File ipf = new File(args[mustStartIdx + 2]);
    File opp = new File(args[mustStartIdx + 3]);
    Configuration conf = this.getConf();

    conf.set(HBaseGraphConstants.HBASE_GRAPH_TABLE_VERTEX_NAME_KEY, vt);
    conf.set(HBaseGraphConstants.HBASE_GRAPH_TABLE_EDGE_NAME_KEY, et);

    // run test threads
    ThreadFactory tf = new DaemonThreadFactory(Executors.defaultThreadFactory());
    ExecutorService pool = Executors.newFixedThreadPool(threads, tf);
    @SuppressWarnings("rawtypes")
    List<Future> fs = new ArrayList<Future>();
    @SuppressWarnings("rawtypes")
    Future f = null;

    for (int a = 0; a < threads; a++) {
        fs.add(pool.submit(new Task(ipf, opp, conf, level, isMs)));
        synchronized (this) {
            wait(interval);
        }
    }

    while (fs.size() > 0) {
        f = fs.get(0);
        f.get();
        if (f.isDone()) {
            if (f.isCancelled()) {
                LOGGER.warn("a future:" + f + " was cancelled !!");
            }
            fs.remove(0);
        }
    }

    return 0;
}

From source file:org.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrClient.java

private RequestTaskState getResponseIfReady(ExecutorCompletionService<RequestTaskState> executer,
        int backupDelay) throws SolrException {

    Future<RequestTaskState> taskInProgress = null;
    try {//from ww  w  . ja v  a  2  s. co m
        if (backupDelay < 0) {
            taskInProgress = executer.take();
        } else {
            taskInProgress = executer.poll(backupDelay, TimeUnit.MILLISECONDS);
        }
        // could be null if poll time exceeded in which case return null.
        if (taskInProgress != null && !taskInProgress.isCancelled()) {
            RequestTaskState resp = taskInProgress.get();

            return resp;
        }
    } catch (InterruptedException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    } catch (ExecutionException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    }
    return null;

}

From source file:com.blacklocus.qs.worker.WorkerQueueItemHandler.java

@SuppressWarnings("unchecked")
@Override//  ww  w  .j  a  va2 s. c  o  m
public void withFuture(QSTaskModel task, final Future<Pair<QSTaskModel, Object>> future) {
    // I don't know if this is useful or not.

    QSWorker worker = workers.get(task.handler);
    if (worker == null) {
        throw new RuntimeException("No worker available for worker identifier: " + task.handler);
    }

    final TaskKitFactory factory = new TaskKitFactory(task, worker, logService, workerIdService);
    worker.withFuture(factory, new Future<Pair<TaskKitFactory, Object>>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        @Override
        public boolean isCancelled() {
            return future.isCancelled();
        }

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public Pair<TaskKitFactory, Object> get() throws InterruptedException, ExecutionException {
            Pair<QSTaskModel, Object> theFuture = future.get();
            return Pair.of(factory, theFuture.getRight());
        }

        @Override
        public Pair<TaskKitFactory, Object> get(long timeout,
                @SuppressWarnings("NullableProblems") TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            Pair<QSTaskModel, Object> theFuture = future.get(timeout, unit);
            return Pair.of(factory, theFuture.getRight());
        }
    });
}

From source file:com.tc.stats.DSO.java

@Override
public Map<ObjectName, Object> invoke(Set<ObjectName> onSet, String operation, long timeout, TimeUnit unit,
        Object[] args, String[] sigs) {
    Map<ObjectName, Object> result = new HashMap<ObjectName, Object>();
    List<Callable<SimpleInvokeResult>> tasks = new ArrayList<Callable<SimpleInvokeResult>>();
    Iterator<ObjectName> onIter = onSet.iterator();
    while (onIter.hasNext()) {
        tasks.add(new SimpleInvokeTask(onIter.next(), operation, args, sigs));
    }/* w w w .ja v a 2 s.  com*/
    try {
        List<Future<SimpleInvokeResult>> results = pool.invokeAll(tasks, timeout, unit);
        Iterator<Future<SimpleInvokeResult>> resultIter = results.iterator();
        while (resultIter.hasNext()) {
            Future<SimpleInvokeResult> future = resultIter.next();
            if (future.isDone() && !future.isCancelled()) {
                try {
                    SimpleInvokeResult sir = future.get();
                    result.put(sir.objectName, sir.result);
                } catch (CancellationException ce) {
                    /**/
                } catch (ExecutionException ee) {
                    /**/
                }
            }
        }
    } catch (InterruptedException ie) {/**/
    }
    return result;
}

From source file:com.tc.stats.DSO.java

@Override
public Map<ObjectName, Map<String, Object>> getAttributeMap(Map<ObjectName, Set<String>> attributeMap,
        long timeout, TimeUnit unit) {
    Map<ObjectName, Map<String, Object>> result = new HashMap<ObjectName, Map<String, Object>>();
    List<Callable<SourcedAttributeList>> tasks = new ArrayList<Callable<SourcedAttributeList>>();
    Iterator<Entry<ObjectName, Set<String>>> entryIter = attributeMap.entrySet().iterator();
    while (entryIter.hasNext()) {
        Entry<ObjectName, Set<String>> entry = entryIter.next();
        tasks.add(new AttributeListTask(entry.getKey(), entry.getValue()));
    }/*w  ww. jav  a2s. co  m*/
    try {
        List<Future<SourcedAttributeList>> results = pool.invokeAll(tasks, timeout, unit);
        Iterator<Future<SourcedAttributeList>> resultIter = results.iterator();
        while (resultIter.hasNext()) {
            Future<SourcedAttributeList> future = resultIter.next();
            if (future.isDone() && !future.isCancelled()) {
                try {
                    SourcedAttributeList sal = future.get();
                    Iterator<Object> attrIter = sal.attributeList.iterator();
                    Map<String, Object> onMap = new HashMap<String, Object>();
                    while (attrIter.hasNext()) {
                        Attribute attr = (Attribute) attrIter.next();
                        onMap.put(attr.getName(), attr.getValue());
                    }
                    result.put(sal.objectName, onMap);
                } catch (CancellationException ce) {
                    /**/
                } catch (ExecutionException ee) {
                    /**/
                }
            }
        }
    } catch (InterruptedException ie) {/**/
    }
    return result;
}