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:com.netflix.curator.framework.recipes.shared.TestSharedCount.java

@Test
public void testMultiClients() throws Exception {
    final int CLIENT_QTY = 5;

    List<Future<List<Integer>>> futures = Lists.newArrayList();
    final List<CuratorFramework> clients = new CopyOnWriteArrayList<CuratorFramework>();
    try {//from  w  ww  . ja v a 2s.  c  o m
        final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY);
        final Semaphore semaphore = new Semaphore(0);
        ExecutorService service = Executors
                .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build());
        for (int i = 0; i < CLIENT_QTY; ++i) {
            Future<List<Integer>> future = service.submit(new Callable<List<Integer>>() {
                @Override
                public List<Integer> call() throws Exception {
                    final List<Integer> countList = Lists.newArrayList();
                    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                            new RetryOneTime(1));
                    clients.add(client);
                    client.start();

                    SharedCount count = new SharedCount(client, "/count", 10);

                    final CountDownLatch latch = new CountDownLatch(1);
                    count.addListener(new SharedCountListener() {
                        @Override
                        public void countHasChanged(SharedCountReader sharedCount, int newCount)
                                throws Exception {
                            if (newCount < 0) {
                                latch.countDown();
                            } else {
                                countList.add(newCount);
                            }

                            semaphore.release();
                        }

                        @Override
                        public void stateChanged(CuratorFramework client, ConnectionState newState) {
                        }
                    });
                    count.start();
                    startLatch.countDown();
                    latch.await();
                    return countList;
                }
            });
            futures.add(future);
        }

        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        clients.add(client);
        client.start();

        Assert.assertTrue(startLatch.await(10, TimeUnit.SECONDS));

        SharedCount count = new SharedCount(client, "/count", 10);
        count.start();

        List<Integer> countList = Lists.newArrayList();
        Random random = new Random();
        for (int i = 0; i < 100; ++i) {
            Thread.sleep(random.nextInt(10));

            int next = random.nextInt(100);
            countList.add(next);
            count.setCount(next);

            Assert.assertTrue(semaphore.tryAcquire(CLIENT_QTY, 10, TimeUnit.SECONDS));
        }
        count.setCount(-1);

        for (Future<List<Integer>> future : futures) {
            List<Integer> thisCountList = future.get();
            Assert.assertEquals(thisCountList, countList);
        }
    } finally {
        for (CuratorFramework client : clients) {
            IOUtils.closeQuietly(client);
        }
    }
}

From source file:com.alibaba.cobar.client.merger.ConcurrentSortMerger.java

public List<E> merge(List<List<E>> entities) {
    List<E> resultList = new ArrayList<E>();
    if (CollectionUtils.isNotEmpty(entities)) {
        if (entities.size() == 1) {
            resultList.addAll(entities.get(0));
        } else {/*from  w ww.  java 2  s  .  c  o  m*/
            List<List<E>> partialResult = new ArrayList<List<E>>();
            int pairs = entities.size() / 2;
            List<Future<List<E>>> futures = new ArrayList<Future<List<E>>>();

            for (int i = 0; i < pairs; i++) {
                final List<E> llst = entities.get(i * 2);
                final List<E> rlst = entities.get(i * 2 + 1);
                futures.add(getExecutor().submit(new Callable<List<E>>() {
                    public List<E> call() throws Exception {
                        return partialSortMerge(llst, rlst);
                    }
                }));
            }

            for (Future<List<E>> f : futures) {
                try {
                    partialResult.add(f.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

            if (entities.size() % 2 == 1) {
                partialResult.add(entities.get(pairs * 2));
            }

            resultList.addAll(merge(partialResult));
        }
    }
    return resultList;
}

From source file:com.simplymeasured.prognosticator.HiveWriterImpl.java

@Override
public void writeRow(final String tableName, Map<String, Object> entity) throws Exception {
    HCatTable table = tableHandleCache.get(tableName, new Callable<HCatTable>() {
        @Override/*from w w w.  j  a v a 2s.  c  om*/
        public HCatTable call() throws Exception {
            return hcatClient.getTable("default", tableName);
        }
    });

    String hbaseTableName = HiveUtils.getTableName(table);

    HTableInterface tableInterface = new HTable(hbaseConfiguration, tableName);
    tableInterface.setAutoFlush(true);

    Serializer serializer = new Serializer(table);

    try {
        List<HCatFieldSchema> columns = table.getCols();

        HCatFieldSchema keyColumn = columns.get(0);

        Put put;

        final byte[] rowkey;

        final List<String> keyRequiredColumns = Lists.newArrayList();

        if (keyColumn.getType() == HCatFieldSchema.Type.STRUCT) {
            HCatSchema keySchema = keyColumn.getStructSubSchema();

            for (HCatFieldSchema fieldSchema : keySchema.getFields()) {
                keyRequiredColumns.add(fieldSchema.getName());
            }

            rowkey = serializer.serializeHiveType(keyColumn, null, entity, 1);
        } else {
            keyRequiredColumns.add(keyColumn.getName());

            rowkey = serializer.serializeHiveType(keyColumn, null, entity.get(keyColumn.getName()), 1);
        }

        if (rowkey == null || rowkey.length == 0) {
            throw new IllegalArgumentException(
                    String.format("Rowkey is null, required key fields missing: %s", keyRequiredColumns));
        }

        put = new Put(rowkey);

        for (int i = 1; i < columns.size(); i++) {
            HCatFieldSchema columnSchema = columns.get(i);

            serializer.serialize(columnSchema, i, put, entity.get(columnSchema.getName()), 1);
        }

        tableInterface.put(put);
    } finally {
        tableInterface.close();
    }
}

From source file:com.fengduo.bee.service.impl.message.MailServiceImpl.java

/**
 * curl -d 'appid=10490&to=zxc<zhangxiongcai337@163.com> &subject=testing
 * Subject&text=testing text/*w w  w  .  jav a  2s .c  o  m*/
 * body&from=zhangxiongcai@fengduo.co&signature=85817
 * b65c1443263c31bf1215fac7c1a' https://api.submail.cn/mail/send.json
 */
@Override
public boolean sendTxtMail(final String toMember, final String subject, final String text) {
    if (StringUtils.isEmpty(toMember)) {
        logger.error("?!??");
        return false;
    }
    if (StringUtils.isEmpty(subject)) {
        logger.error("!??");
        return false;
    }
    if (StringUtils.isEmpty(text)) {
        logger.error("!??");
        return false;
    }
    Future<Boolean> future = executor.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return sendMail(toMember, subject, text);
        }

    });
    try {
        return future.get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:net.eusashead.hateoas.response.argumentresolver.AsyncEntityController.java

@RequestMapping(method = RequestMethod.OPTIONS)
public Callable<ResponseEntity<Entity>> options(final OptionsResponseBuilder<Entity> builder) {

    return new Callable<ResponseEntity<Entity>>() {

        @Override/*from  ww  w .j a v a 2s.com*/
        public ResponseEntity<Entity> call() throws Exception {
            return builder.allow(HttpMethod.GET, HttpMethod.HEAD).entity(new Entity("foo")).build();
        }
    };
}

From source file:com.rogiel.httpchannel.http.Request.java

public Future<String> asStringAsync() throws IOException {
    return ctx.threadPool.submit(new Callable<String>() {
        @Override/*from  w  w  w  .j  a va  2s  .co  m*/
        public String call() throws Exception {
            return asString();
        }
    });
}

From source file:at.beris.virtualfile.client.ftp.FtpClient.java

@Override
public void disconnect() throws IOException {
    LOGGER.info("Disconnecting from " + username() + "@" + host() + ":" + String.valueOf(port()));
    executionHandler(new Callable<Void>() {
        @Override/*w ww  . j  av a 2s.  com*/
        public Void call() throws Exception {
            reconnect = false;
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
            return null;
        }
    });
}

From source file:no.uis.fsws.proxy.StudinfoProxyImpl.java

@Override
public List<Studieprogram> getStudieprogrammerForOrgenhet(final XMLGregorianCalendar arstall,
        final Terminkode terminkode, final Sprakkode sprak, final int institusjonsnr, final Integer fakultetsnr,
        final Integer instituttnr, final Integer gruppenr, final boolean medUPinfo) {
    final StudInfoImport svc = getServiceForPrincipal();

    try {/*from  w ww . j  a  v  a  2  s  . c  om*/
        Future<List<Studieprogram>> future = executor.submit(new Callable<List<Studieprogram>>() {

            @Override
            public List<Studieprogram> call() throws Exception {
                final FsStudieinfo sinfo = svc.fetchStudyPrograms(institusjonsnr,
                        fakultetsnr != null ? fakultetsnr : -1, arstall.getYear(), terminkode.toString(),
                        medUPinfo, sprak.toString());
                return sinfo.getStudieprogram();
            }
        });

        return future.get(timeoutMinutes, TimeUnit.MINUTES);
    } catch (ExecutionException | InterruptedException | TimeoutException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.scripps.fl.pubchem.EUtilsFactory.java

public Callable<InputStream> getInputStream(final String url, final Object... params) throws IOException {
    return new Callable<InputStream>() {
        public InputStream call() throws Exception {
            StringBuffer sb = new StringBuffer();
            sb.append(url).append("?");
            PostMethod post = new PostMethod(url);
            List<NameValuePair> data = new ArrayList<NameValuePair>();
            data.add(new NameValuePair("tool", EUtilsFactory.this.tool));
            data.add(new NameValuePair("email", EUtilsFactory.this.email));
            for (int ii = 0; ii < params.length; ii += 2) {
                String name = params[ii].toString();
                String value = "";
                if ((ii + 1) < params.length)
                    value = params[ii + 1].toString();
                data.add(new NameValuePair(name, value));
                sb.append(name).append("=").append(value).append("&");
            }/*from  www.  jav a 2  s . c  o m*/
            post.setRequestBody(data.toArray(new NameValuePair[0]));
            HttpClient httpclient = new HttpClient();
            int result = httpclient.executeMethod(post);
            //            log.debug("Fetching from: " + url + StringUtils.join(params, " "));
            log.debug("Fetching from: " + sb);
            InputStream in = post.getResponseBodyAsStream();
            return in;
        }
    };
}

From source file:com.google.wave.api.robot.HttpRobotConnection.java

@Override
public ListenableFuture<String> asyncGet(final String url) {
    return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() {
        @Override//w w  w.  j  a va2s. c o m
        public String call() throws RobotConnectionException {
            return get(url);
        }
    }));
}