Example usage for java.util.concurrent Callable Callable

List of usage examples for java.util.concurrent Callable Callable

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:io.joynr.messaging.bounceproxy.monitoring.BounceProxyStartupReporter.java

/**
 * Notifies the monitoring service that a bounce proxy has changed its
 * lifecycle state.<br>/*from  w w w  .java 2 s .  com*/
 * This call starts a loop that tries to send reports to the bounce proxy
 * controller until the bounce proxy is registered at the bounce proxy
 * controller.<br>
 * Startup reporting is done in a separate thread, so that a possibly
 * infinite loop won't block the whole servlet. Especially, this allows the
 * servlet to be stopped at any time.
 */
public void startReporting() {

    // make sure we report the lifecycle event only once
    if (startupEventReported == true) {
        logger.error("startup event has already been reported or is being reported now");
        return;
    }

    startupEventReported = true;

    // the startup event has to be reported in its own thread, as this is
    // done forever. Otherwise a servlet will hang in startup mode forever
    // and can't be stopped by normal admin commands.
    Callable<Boolean> reportEventCallable = new Callable<Boolean>() {

        public Boolean call() {
            try {
                // Notify BPC of BP startup event in a loop.
                if (reportEventLoop()) {
                    // reporting successful within the allowed number of
                    // retries
                    return true;
                }

                // The BPC could not be reached, so return.
                logger.error("Bounce Proxy lifecycle event notification failed. Exiting.");

            } catch (Exception e) {
                logger.error("Uncaught exception in reporting lifecycle event.", e);
            }
            startupEventReported = false;
            return false;
        }
    };

    // don't wait for the callable to end so that shutting down is possible
    // at any time
    startupReportFuture = execService.submit(reportEventCallable);
}

From source file:com.laudandjolynn.mytv.crawler.CrawlerGroup.java

@Override
public List<TvStation> crawlAllTvStation() {
    List<TvStation> resultList = new ArrayList<TvStation>();
    int size = crawlers.size();
    int maxThreadNum = Constant.CPU_PROCESSOR_NUM;
    ThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Mytv_CrawlerGroup_%d")
            .build();//from   w w  w.j  av a  2s .c  o m
    ExecutorService executorService = Executors.newFixedThreadPool(size > maxThreadNum ? maxThreadNum : size,
            threadFactory);
    CompletionService<List<TvStation>> completionService = new ExecutorCompletionService<List<TvStation>>(
            executorService);
    for (final Crawler crawler : crawlers) {
        Callable<List<TvStation>> task = new Callable<List<TvStation>>() {
            @Override
            public List<TvStation> call() throws Exception {
                return crawler.crawlAllTvStation();
            }
        };
        completionService.submit(task);
    }
    executorService.shutdown();
    int count = 0;
    while (count < size) {
        try {
            List<TvStation> stationList = completionService.take().get();
            if (stationList != null) {
                resultList.addAll(stationList);
            }
        } catch (InterruptedException e) {
            logger.error("crawl task of all tv station interrupted.", e);
        } catch (ExecutionException e) {
            logger.error("crawl task of all tv station executed fail.", e);
        }
        count++;
    }

    for (CrawlEventListener listener : listeners) {
        listener.crawlEnd(new AllTvStationCrawlEndEvent(this, resultList));
    }
    return resultList;
}

From source file:com.github.rholder.esthree.command.Get.java

public MessageDigest retryingGet() throws ExecutionException, RetryException {

    return (MessageDigest) RetryUtils.AWS_RETRYER.call(new Callable<Object>() {
        public MessageDigest call() throws Exception {

            GetObjectRequest req = new GetObjectRequest(bucket, key);

            S3Object s3Object = amazonS3Client.getObject(req);
            contentLength = s3Object.getObjectMetadata().getContentLength();
            fullETag = s3Object.getObjectMetadata().getETag();

            Progress progress = new TransferProgressWrapper(new TransferProgress());
            progress.setTotalBytesToTransfer(contentLength);
            if (progressListener != null) {
                progressListener.withTransferProgress(progress).withCompleted(0.0).withMultiplier(1.0);
            }/* w w  w  . j  a  va 2 s . co m*/

            InputStream input = null;
            try {
                // create the output file, now that we know it actually exists
                if (output == null) {
                    output = new RandomAccessFile(outputFile, "rw");
                }

                // seek to the start of the chunk in the file, just in case we're retrying
                output.seek(0);
                input = s3Object.getObjectContent();

                return copyAndHash(input, contentLength, progress);
            } finally {
                IOUtils.closeQuietly(input);
            }
        }
    });
}

From source file:org.cloudfoundry.android.cfdroid.CloudFoundry.java

public CloudApplication bindService(final String application, final String service) {
    return doWithClient(new Callable<CloudApplication>() {
        @Override//w  w  w.  j a  v  a2  s. co m
        public CloudApplication call() throws Exception {
            cache.client.bindService(application, service);
            // Force a reload of that CloudApplication object
            // to reflect the change.
            CloudApplication app = cache.client.getApplication(application);
            cache.updateApp(app);
            return app;
        }
    });
}

From source file:edu.mayo.cts2.framework.webapp.rest.controller.MethodTimingAspect.java

/**
 * Execute./* w  w  w.ja  v a2s.  c o  m*/
 *
 * @param pjp the pjp
 * @return the object
 * @throws Throwable the throwable
 */
@Around("execution(public *"
        + " edu.mayo.cts2.framework.webapp.rest.controller.*.*(..,edu.mayo.cts2.framework.webapp.rest.command.QueryControl,..))")
public Object execute(final ProceedingJoinPoint pjp) throws Throwable {

    QueryControl queryControl = null;

    //this should never happen
    if (ArrayUtils.isEmpty(pjp.getArgs())) {
        throw new IllegalStateException("Pointcut failure!");
    }

    for (Object arg : pjp.getArgs()) {
        if (arg.getClass() == QueryControl.class) {
            queryControl = (QueryControl) arg;
            break;
        }
    }

    //this also should never happen
    if (queryControl == null) {
        throw new IllegalStateException("Pointcut failure!");
    }

    final AtomicLong threadId = new AtomicLong(-1);

    Future<Object> future = this.executorService.submit(new Callable<Object>() {

        @Override
        public Object call() {
            try {
                threadId.set(Thread.currentThread().getId());

                /*
                 * The model here is that we clear any previous timeout before we launch the job. A design flaw is that we
                 * can't tell if we are clearing a previous timeout that simply hadn't been cleaned up yet, or if we are
                 * clearing a timeout meant for this thread that happened before this thread even launched. The second scenario 
                 * seems unlikely as the minimum timeout is 1 second - hard to believe it would take more than 1 second to 
                 * launch this thread. Plus, this thread would have to launch in the exact window in between the timeout and 
                 * the future.cancel()
                 * 
                 * If the above scenario did defy all odds and happen , it shouldn't cause much harm, as the end result would
                 * be that this thread wouldn't see the cancelled flag - and would churn away for no reason, wasting some cpu
                 * cycles, but doing no other harm.
                 */

                Timeout.clearThreadFlag(threadId.get());
                return pjp.proceed();
            } catch (Throwable e) {

                if (e instanceof Error) {
                    throw (Error) e;
                }

                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }

                throw new RuntimeException(e);
            }
        }
    });

    long time = queryControl.getTimelimit();

    try {
        if (time < 0) {
            return future.get();
        } else {
            return future.get(time, TimeUnit.SECONDS);
        }
    } catch (ExecutionException e) {
        throw e.getCause();
    } catch (TimeoutException e) {
        try {
            //Set the flag for the processing thread to read
            Timeout.setTimeLimitExceeded(threadId.get());

            //Schedule another future to make sure we don't cause a memory leak if the thread IDs aren't being reused (though, they should be)
            //and therefore don't get cleared up by the next run.  Give the running thread 30 seconds to see the cancelled flag before this 
            //cleanup takes place.
            this.scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                    Timeout.clearThreadFlag(threadId.get());
                }
            }, 30, TimeUnit.SECONDS);

            //Interrupt the processing thread so it has an opportunity to check the flag and stop.
            future.cancel(true);
        } catch (Exception e1) {
            // don't think this is possible, but just in case...
        }
        throw ExceptionFactory.createTimeoutException(e.getMessage());
    }
}

From source file:com.parse.FileObjectStore.java

@Override
public Task<Void> deleteAsync() {
    return Task.call(new Callable<Void>() {
        @Override/*from   w ww  . j  a v  a 2  s .com*/
        public Void call() throws Exception {
            if (file.exists() && !ParseFileUtils.deleteQuietly(file)) {
                throw new RuntimeException("Unable to delete");
            }

            return null;
        }
    }, ParseExecutors.io());
}

From source file:org.netxilia.spi.impl.formula.FormulaCalculatorActor.java

@Override
public IListenableFuture<CellData> sendCalculate() {
    if (calculationResult != null) {
        throw new IllegalStateException("A calculation is already ongoing");
    }// w w w . ja v a2s . c o m
    // TODO check here if the executor cannot return directly the needed future
    calculationResult = new MutableFuture<CellData>();
    executor.submit(new CallableWithUser<CellData>(userService, new Callable<CellData>() {
        @Override
        public CellData call() {
            loadData();
            return null;
        }

    }));

    return calculationResult;
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

@Override
public ListenableFuture<Response> request(final URI uri, final String method, final byte[] entityBytes,
        final Map<String, List<String>> headers) {
    return executorService.submit(new Callable<Response>() {
        @Override/*from  ww  w . ja  v a  2  s. c o  m*/
        public Response call() throws Exception {
            final HttpURLConnection connection = connect(uri, method, entityBytes, headers);
            final int status = connection.getResponseCode();
            final InputStream rawStream;

            if (status / 100 != 2) {
                rawStream = connection.getErrorStream();
            } else {
                rawStream = connection.getInputStream();
            }

            final boolean gzip = isGzipCompressed(connection);
            final InputStream stream = gzip ? new GZIPInputStream(rawStream) : rawStream;
            final ByteArrayOutputStream payload = new ByteArrayOutputStream();
            if (stream != null) {
                int n;
                byte[] buffer = new byte[4096];
                while ((n = stream.read(buffer, 0, buffer.length)) != -1) {
                    payload.write(buffer, 0, n);
                }
            }

            URI realUri = connection.getURL().toURI();
            if (log.isTraceEnabled()) {
                log.trace("rep: {} {} {} {} {} gzip:{}", method, realUri, status, payload.size(),
                        decode(payload), gzip);
            } else {
                log.debug("rep: {} {} {} {} gzip:{}", method, realUri, status, payload.size(), gzip);
            }

            return new Response(method, uri, status, payload.toByteArray(),
                    Collections.unmodifiableMap(Maps.newHashMap(connection.getHeaderFields())));
        }

        private boolean isGzipCompressed(final HttpURLConnection connection) {
            final List<String> encodings = connection.getHeaderFields().get("Content-Encoding");
            if (encodings == null) {
                return false;
            }
            for (String encoding : encodings) {
                if ("gzip".equals(encoding)) {
                    return true;
                }
            }
            return false;
        }
    });
}

From source file:org.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java

public void testInstanceManagerSeparateThread() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");
    try {/* www  . j a  v  a  2s  .  co  m*/

        final IInstanceManager instanceManager = (IInstanceManager) context.getBean("instanceManager");

        final String pid1 = instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "one");
        IInstance instance = instanceManager.getInstance(pid1);
        assertNotNull(instance);

        instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two");
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>(
                new LinkedList<String>());
        Future<Object> future1 = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                return instanceManager.doWithInstance(pid1, new IInstanceCallback() {
                    public IExecutorResult execute(IInstance instance) throws Exception {
                        log.info("locking one");
                        Thread.sleep(2000);
                        results.get().add("one");
                        return new IgnoredResult("", "", "");
                    }
                });
            }

        });
        Thread.sleep(100);
        assertNotNull(future1.get());
    } finally {
        context.destroy();
    }
}

From source file:com.netflix.curator.TestSessionFailRetryLoop.java

@Test
public void testRetryStatic() throws Exception {
    Timing timing = new Timing();
    final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(),
            timing.session(), timing.connection(), null, new RetryOneTime(1));
    SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
    retryLoop.start();/*  w w w. j ava 2s .c  o m*/
    try {
        client.start();
        final AtomicBoolean secondWasDone = new AtomicBoolean(false);
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.RETRY, new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        if (firstTime.compareAndSet(true, false)) {
                            Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                            KillSession.kill(client.getZooKeeper(), server.getConnectString());
                            client.getZooKeeper();
                            client.blockUntilConnectedOrTimedOut();
                        }

                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        return null;
                    }
                });

                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        Assert.assertFalse(firstTime.get());
                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        secondWasDone.set(true);
                        return null;
                    }
                });
                return null;
            }
        });

        Assert.assertTrue(secondWasDone.get());
    } finally {
        retryLoop.close();
        IOUtils.closeQuietly(client);
    }
}