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.alibaba.dubbo.examples.async.AsyncConsumer.java

public static void main(String[] args) throws Exception {
    String config = AsyncConsumer.class.getPackage().getName().replace('.', '/') + "/async-consumer.xml";
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
    context.start();/*from ww  w  .  j av  a 2 s . c o m*/

    final AsyncService asyncService = (AsyncService) context.getBean("asyncService");

    Future<String> f = RpcContext.getContext().asyncCall(new Callable<String>() {
        public String call() throws Exception {
            return asyncService.sayHello("async call request");
        }
    });

    System.out.println("async call ret :" + f.get());

    RpcContext.getContext().asyncCall(new Runnable() {
        public void run() {
            asyncService.sayHello("oneway call request1");
            asyncService.sayHello("oneway call request2");
        }
    });

    System.in.read();
}

From source file:locking.LockingExample.java

public static void main(String[] args) throws Exception {
    // all of the useful sample code is in ExampleClientThatLocks.java

    // FakeLimitedResource simulates some external resource that can only be access by one process at a time
    final FakeLimitedResource resource = new FakeLimitedResource();

    ExecutorService service = Executors.newFixedThreadPool(QTY);
    final TestingServer server = new TestingServer();
    try {//  w  ww.  ja v  a2  s .c  o m
        for (int i = 0; i < QTY; ++i) {
            final int index = i;
            Callable<Void> task = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                            new ExponentialBackoffRetry(1000, 3));
                    try {
                        client.start();

                        ExampleClientThatLocks example = new ExampleClientThatLocks(client, PATH, resource,
                                "Client " + index);
                        for (int j = 0; j < REPETITIONS; ++j) {
                            example.doWork(10, TimeUnit.SECONDS);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            };
            service.submit(task);
        }

        service.shutdown();
        service.awaitTermination(10, TimeUnit.MINUTES);
    } finally {
        IOUtils.closeQuietly(server);
    }
}

From source file:com.cedarsoft.serialization.SplittingPerformanceRunner.java

public static void main(String[] args) throws Exception {
    final String uri = "http://www.cedarsoft.com/some/slashes/1.0.0";

    run("String.plit", new Callable<String>() {
        @Override//from w ww .j  a  va  2 s  . c o  m
        public String call() throws Exception {
            String[] parts = uri.split("/");
            return parts[parts.length - 1];
        }
    });

    run("Splitter", new Callable<String>() {
        @Override
        public String call() throws Exception {
            Splitter splitter = Splitter.on("/");
            Iterable<String> parts = splitter.split(uri);

            Iterator<String> iterator = parts.iterator();
            while (true) {
                String current = iterator.next();
                if (!iterator.hasNext()) {
                    return current;
                }
            }
        }
    });

    run("static Splitter", new Callable<String>() {
        @Override
        public String call() throws Exception {
            Iterable<String> parts = SPLITTER.split(uri);

            Iterator<String> iterator = parts.iterator();
            while (true) {
                String current = iterator.next();
                if (!iterator.hasNext()) {
                    return current;
                }
            }
        }
    });

    run("indexOf", new Callable<String>() {
        @Override
        public String call() throws Exception {
            int index = uri.lastIndexOf("/");
            return uri.substring(index + 1);
        }
    });
}

From source file:com.yufei.dataget.dataretriver.HttpDataRetriverUsingFirefoxDriver.java

public static void main(String[] args) throws Exception {

    final long startTime = System.currentTimeMillis();
    mLog.info("calling runWithTimeout!");
    HttpDataRetriverUsingFirefoxDriver hdrufd = new HttpDataRetriverUsingFirefoxDriver(null);

    try {/*  ww  w.jav a2 s. com*/
        String htmlContent = TimeOutUtils.runWithTimeout(new Callable<String>() {

            @Override
            public String call() throws Exception {
                String url = "http://www.baidu.com/tools?url=http%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DO0urTq_fyCkG3Rd2veZDQm7TLJ50XyUOeeoybddPUG6zBjpgh37XHtMM_oXKe4nQxM-q5IEVjldslw0tbkMfvK&jump=http%3A%2F%2Fkoubei.baidu.com%2Fwomc%2Fp%2Fsentry%3Ftitle%3D%012014%01-%012015%01%E5%B9%B4%E5%BA%A6%01QS%01%E4%B8%96%E7%95%8C%01%E6%8E%92%E5%90%8D%01%3A%01%E6%BE%B3%E5%A4%A7%E5%88%A9%E4%BA%9A%01%E5%A4%A7%E5%AD%A6%0123%01%E6%89%80%01%E9%AB%98%E6%A0%A1%01%E8%BF%9B%E5%85%A5%02TOP%01500%03-%01%E7%95%99%E5%AD%A6%01-%01...%26q%3Dtop%20500%20university&key=surl";
                hdrufd.setUrl(new URL(url));
                hdrufd.connect();

                System.out.print(hdrufd.getHtmlContent());
                return hdrufd.getHtmlContent();

            }
        }, 10, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        mLog.info("got timeout!");
    } finally {
        hdrufd.disconnect();

    }
    mLog.info("end of main method!");

}

From source file:com.barchart.udt.AppServer.java

public static void main(final String[] args) throws IOException {

    int port = 9000;

    if (args.length > 1) {
        System.out.println("usage: appserver [server_port]");
        return;/*from   w w w. j a va  2  s  .  c  o  m*/
    }

    if (args.length == 1) {
        port = Integer.parseInt(args[0]);
    }

    final NetServerSocketUDT acceptorSocket = new NetServerSocketUDT();
    acceptorSocket.bind(new InetSocketAddress(getLocalHost(), port), 256);

    System.out.printf("server is ready at port: %d\n", port);
    System.out.println("server is ready");
    while (true) {

        final Socket clientSocket = acceptorSocket.accept();

        // Start the read ahead background task
        Executors.newSingleThreadExecutor().submit(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                return clientTask(clientSocket);
            }
        });
    }
}

From source file:ec.util.chart.swing.JTimeSeriesRendererSupportDemo.java

public static void main(String[] args) {
    new BasicSwingLauncher().content(JTimeSeriesRendererSupportDemo.class).title("Support Demo")
            .icons(new Callable<List<Image>>() {
                @Override/*  w w  w . j  a  va  2s.com*/
                public List<Image> call() throws Exception {
                    Color c = new Color(TangoColorScheme.DARK_SKY_BLUE);
                    return FontAwesome.FA_TACHOMETER.getImages(c, 16f, 32f, 64f);
                }
            }).launch();
}

From source file:com.rk.grid.federation.FederatedCluster.java

/**
 * @param args/*from   w  w w .j a v a  2s. c o m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    int port = Integer.parseInt(args[0]);
    String clusterName = args[1];
    String masterBrokerServiceName = args[2];
    int masterPort = Integer.parseInt(args[3]);
    String masterHost = args[4];

    IBroker<Object> masterBroker = null;
    for (int i = 0; i < 100; i++) {
        try {
            masterBroker = getConnection(masterBrokerServiceName, masterPort, masterHost);
            if (masterBroker != null)
                break;
        } catch (RemoteLookupFailureException e) {
            if (i % 100 == 0)
                System.out.println("Sleeping....");
        }
        Thread.sleep(100);
    }

    if (masterBroker == null)
        throw new RuntimeException("Unable to find master broker " + masterBrokerServiceName);

    BrokerInfo brokerInfo = masterBroker.getBrokerInfo();
    GridConfig gridConfig = brokerInfo.getConfig();
    List<String> jvmNodeParams = masterBroker.getBrokerInfo().getJvmNodeParams();
    GridExecutorService cluster = new GridExecutorService(port, jvmNodeParams, gridConfig, clusterName);
    cluster.getBroker().unPause();

    final TaskExecutor taskExecutor = new TaskExecutor(cluster);

    final IRemoteResultsHandler<Object> callback = masterBroker.getCallback();
    IWorkQueue<Object> workQueue = masterBroker.getWorkQueue();

    ExecutorService pool = Executors.newFixedThreadPool(3);

    masterBroker.unPause();

    while (!Thread.currentThread().isInterrupted()) {
        final IExecutable<?> executable = workQueue.take();

        if (executable == null)
            continue;

        if (executable.equals(IExecutable.POISON)) {
            break;
        }

        Callable<Object> callable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Future<ITaskResult<?>> future = taskExecutor.submit(executable);
                ITaskResult<?> iResult = future.get();

                String uid = executable.getUID();
                try {
                    callback.accept(new RemoteResult<Object>(iResult, uid));
                } catch (Throwable t) {
                    t.printStackTrace();
                    try {
                        callback.accept(new RemoteResult<Object>(
                                new RemoteExecutorException("Error execution remote task '" + uid + "'", t),
                                uid));
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                }
                return null;
            }

        };

        pool.submit(callable);
    }
    pool.shutdown();
    taskExecutor.shutdown();
    System.out.println("Finished...!");
}

From source file:ParallelizedMatrixProduct.java

public static void main(String args[]) throws Exception {

    System.setSecurityManager(new YesSecurityManager());

    double[][] matrix1 = new double[MATRIX_SIZE][MATRIX_SIZE];
    double[][] matrix2 = new double[MATRIX_SIZE][MATRIX_SIZE];

    for (int i = 0; i < MATRIX_SIZE; ++i)
        for (int j = 0; j < MATRIX_SIZE; ++j) {
            matrix1[i][j] = Math.round(Math.random() * MATRIX_ELEMENT_MAX_VALUE);
            matrix2[i][j] = Math.round(Math.random() * MATRIX_ELEMENT_MAX_VALUE);
        }//from  w ww . j a va  2  s  .  c om

    ExecutorService exec = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    Future<Double>[][] futures = new Future[MATRIX_SIZE][MATRIX_SIZE];
    for (int i = 0; i < MATRIX_SIZE; ++i) {
        for (int j = 0; j < MATRIX_SIZE; ++j) {
            final double[] v1 = getRow(matrix1, i);
            final double[] v2 = getColumn(matrix2, j);

            if (i % 2 == 0) {
                futures[i][j] = exec.submit(new Callable<Double>() {
                    public Double call() {

                        RPFSessionInfo.get().put("USER", "USER FOR " + Thread.currentThread().getName());
                        RServices rp = null;
                        int replayCounter = NBR_REPLAY_ON_FAILURE;

                        while (replayCounter >= 0) {

                            try {

                                rp = (RServices) org.kchine.rpf.ServantProviderFactory.getFactory()
                                        .getServantProvider().borrowServantProxy();

                                rp.putAndAssign(new RNumeric(v1), "rv1");
                                rp.putAndAssign(new RNumeric(v2), "rv2");
                                RMatrix res = ((RMatrix) rp.getObject("rv1%*%rv2"));

                                return ((RNumeric) res.getValue()).getValue()[0];

                            } catch (TimeoutException e) {
                                e.printStackTrace();
                                return null;
                            } catch (RemoteException re) {
                                re.printStackTrace();
                                --replayCounter;

                            } finally {

                                try {
                                    if (rp != null) {
                                        ServantProviderFactory.getFactory().getServantProvider()
                                                .returnServantProxy(rp);
                                        log.info("<" + Thread.currentThread().getName()
                                                + "> returned resource : " + rp.getServantName());
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                        }

                        return null;

                    }
                });
            } else {
                futures[i][j] = exec.submit(new Callable<Double>() {
                    public Double call() {

                        try {
                            return vecprod(v1, v2);
                        } finally {
                            log.info("<" + Thread.currentThread().getName() + "> Java task ended successfully");
                        }
                    }
                });
            }
        }

    }

    while (true) {
        if (countDone(futures) == (MATRIX_SIZE * MATRIX_SIZE))
            break;
        try {
            Thread.sleep(20);
        } catch (Exception e) {
        }
    }

    log.info(" done --  product matrix -->");

    Double[][] matrix1_x_matrix2 = new Double[MATRIX_SIZE][MATRIX_SIZE];
    for (int i = 0; i < MATRIX_SIZE; ++i)
        for (int j = 0; j < MATRIX_SIZE; ++j)
            matrix1_x_matrix2[i][j] = futures[i][j].get();

    System.out.println(showMatrix(matrix1, "M1"));
    System.out.println(showMatrix(matrix2, "M2"));
    System.out.println(showMatrix(matrix1_x_matrix2, "M1 x M2"));

    System.exit(0);
}

From source file:org.excalibur.benchmark.test.EC2InstancesBenchmark.java

public static void main(String[] args) throws IOException {
    final String benchmark = "sp";
    final String outputDir = "/home/alessandro/excalibur/source/services/benchmarks/ec2/";

    final String[] scripts = {
            readLines(getDefaultClassLoader()
                    .getResourceAsStream("org/excalibur/service/deployment/resource/script/iperf3.sh")),
            readLines(getDefaultClassLoader()
                    .getResourceAsStream("org/excalibur/service/deployment/resource/script/linkpack.sh")),
            readLines(getDefaultClassLoader().getResourceAsStream(
                    "org/excalibur/service/deployment/resource/script/benchmarks/run_linpack_xeon64.sh")), };

    final String[] instanceTypes = { "c3.8xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "i2.xlarge" };

    final String privateKeyMaterial = IOUtils2
            .readLines(new File(SystemUtils2.getUserDirectory(), "/.ec2/leite.pem"));
    final File sshKey = new File(SystemUtils2.getUserDirectory(), "/.ec2/leite.pem");
    Properties properties = Properties2
            .load(getDefaultClassLoader().getResourceAsStream("aws-config.properties"));

    final LoginCredentials loginCredentials = new LoginCredentials.Builder()
            .identity(properties.getProperty("aws.access.key"))
            .credential(properties.getProperty("aws.secret.key")).credentialName("leite").build();

    final UserProviderCredentials userProviderCredentials = new UserProviderCredentials()
            .setLoginCredentials(loginCredentials)
            .setRegion(new Region("us-east-1").setEndpoint("https://ec2.us-east-1.amazonaws.com"));

    final EC2 ec2 = new EC2(userProviderCredentials);

    List<Callable<Void>> tasks = Lists.newArrayList();

    for (final String instanceType : instanceTypes) {
        tasks.add(new Callable<Void>() {
            @Override/*from  w w  w .j  a va 2s . com*/
            public Void call() throws Exception {
                InstanceTemplate template = new InstanceTemplate().setImageId("ami-864d84ee")
                        .setInstanceType(InstanceType.valueOf(instanceType)).setKeyName("leite")
                        .setLoginCredentials(
                                loginCredentials.toBuilder().privateKey(privateKeyMaterial).build())
                        .setGroup(new org.excalibur.core.cloud.api.Placement().setZone("us-east-1a")) //.setGroupName("iperf-bench")
                        .setMinCount(1).setMaxCount(1)
                        .setInstanceName(String.format("%s-%s", instanceType, benchmark))
                        .setRegion(userProviderCredentials.getRegion()).setTags(Tags
                                .newTags(new org.excalibur.core.cloud.api.domain.Tag("benchmark", benchmark)));

                final Instances instances = ec2.createInstances(template);

                for (VirtualMachine instance : instances) {
                    Preconditions.checkState(
                            !Strings.isNullOrEmpty(instance.getConfiguration().getPlatformUserName()));
                    Preconditions.checkState(
                            !Strings.isNullOrEmpty(instance.getConfiguration().getPublicIpAddress()));

                    HostAndPort hostAndPort = fromParts(instance.getConfiguration().getPublicIpAddress(), 22);

                    LoginCredentials sshCredentials = new LoginCredentials.Builder().authenticateAsSudo(true)
                            .privateKey(sshKey).user(instance.getConfiguration().getPlatformUserName()).build();

                    SshClient client = SshClientFactory.defaultSshClientFactory().create(hostAndPort,
                            sshCredentials);
                    client.connect();

                    try {
                        for (int i = 0; i < scripts.length; i++) {
                            ExecutableResponse response = client.execute(scripts[i]);
                            Files.write(response.getOutput().getBytes(), new File(outputDir,
                                    String.format("%s-%s.output.txt", template.getInstanceName(), i)));
                            LOG.info(
                                    "Executed the script [{}] with exit code [{}], error [{}], and output [{}] ",
                                    new Object[] { scripts[i], String.valueOf(response.getExitStatus()),
                                            response.getError(), response.getOutput() });
                        }
                    } finally {
                        client.disconnect();
                    }

                    ec2.terminateInstance(instance);
                }
                return null;
            }
        });
    }

    ListeningExecutorService executor = DynamicExecutors
            .newListeningDynamicScalingThreadPool("benchmark-instances-thread-%d");

    Futures2.invokeAllAndShutdownWhenFinish(tasks, executor);

    ec2.close();
}

From source file:Main.java

public static Callable<Object> getCallable(final int seconds) {
    return new Callable<Object>() {
        @Override/*  ww  w  .j av a  2  s. co  m*/
        public Object call() throws Exception {
            Thread.sleep(seconds * 1000);
            return seconds + "s pause finished";
        }
    };
}