Example usage for java.util.concurrent Executors newCachedThreadPool

List of usage examples for java.util.concurrent Executors newCachedThreadPool

Introduction

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

Prototype

public static ExecutorService newCachedThreadPool() 

Source Link

Document

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

Usage

From source file:Main.java

public static String getDomainAddress(final String domain) {
    try {/*from   w ww .  j a  v  a2s . c om*/
        ExecutorService exec = Executors.newCachedThreadPool();
        Future<String> fs = exec.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                InetAddress inetAddress;
                try {
                    inetAddress = InetAddress.getByName(domain);
                    return inetAddress.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        return fs.get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

/**
 * Singleton access to the threadpool scheduler
 *///ww  w. j a  v  a 2 s  .c o m
public static ExecutorService getScheduler() {
    synchronized (syncRoot) {
        if (null == scheduler) {
            scheduler = Executors.newCachedThreadPool();
        }
        return scheduler;
    }
}

From source file:Main.java

public static <T, R> ListenableFuture<List<R>> parallelTransform(Collection<T> input,
        final Function<T, R> function) {
    final ExecutorService pool = Executors.newCachedThreadPool();
    return parallelTransform(input, function, pool);
}

From source file:Main.java

public static <T> List<Future<T>> call(Collection<Callable<T>> callables) {
    ExecutorService es = Executors.newCachedThreadPool();
    List<Future<T>> list = Lists.newArrayList();
    for (Callable<T> callable : callables) {
        list.add(es.submit(callable));/* w  ww.  j a  v  a2 s.  c om*/
    }
    return list;
}

From source file:Main.java

public static <T> Future<T> exec(Callable<T> callable) {
    return Executors.newCachedThreadPool().submit(callable);
}

From source file:ke.co.binary.app.restoppress.restoppress.Service.ImplGenRequests.java

@Override
public void sendRequests(int number, String url, Reply json_obj, String method) {

    long starttime = System.currentTimeMillis();
    ExecutorService executor = Executors.newCachedThreadPool();
    for (int i = 0; i < number; i++) {
        //generate random ref code and order info
        json_obj.getMessage().setReferenceNo(generateRandom());
        json_obj.getMessage().setOrderInfo(generateRandom());
        //System.out.println("Request Method: "+json_obj.getMessage());
        Runnable worker = new ProcessRequest(url, method, json_obj);
        executor.execute(worker);//from   w  w  w  . j  av  a  2s  . co m
    }
    executor.shutdown();
    //wait for all the threads to terminate
    while (!executor.isTerminated()) {
    }
    long finishtime = System.currentTimeMillis();
    time_taken = (finishtime - starttime);

}

From source file:com.webcrawler.manager.impl.ImageManagerImpl.java

public ImageManagerImpl() {
    executorService = Executors.newCachedThreadPool();
}

From source file:com.android.pchelper.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.
 */
public AsyncHttpClient() {
    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
}

From source file:com.qwazr.search.bench.test.Merging.MergingTest.java

@BeforeClass
public static void setup() {
    executorService = Executors.newCachedThreadPool();

    // Let's build a dictionary of terms
    dictionary = new String[100_000];
    for (int i = 0; i < dictionary.length; i++)
        dictionary[i] = RandomUtils.alphanumeric(RandomUtils.nextInt(TERM_MIN_SIZE, TERM_MAX_SIZE));
    distribution = new ZipfDistribution(dictionary.length, 1.07f);
}

From source file:fr.inria.edelweiss.kgdqp.core.FedInferrencingCLI.java

public static void main(String args[]) throws ParseException, EngineException, InterruptedException {

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;// w  w w.  j  av  a2 s  .c  o  m
    boolean rulesSelection = false;
    File rulesDir = null;
    File ontDir = null;

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules");
    Option ontOpt = new Option("o", "ontologiesDir", true,
            "directory containing the ontologies for rules selection");
    //        Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run");
    options.addOption(queryOpt);
    options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(rulesOpt);
    options.addOption(ontOpt);
    //        options.addOption(selOpt);

    String header = "Corese/KGRAM distributed rule engine command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (!cmd.hasOption("e")) {
        logger.info("You must specify at least the URL of one sparql endpoint !");
        System.exit(0);
    } else {
        endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e")));
    }
    if (cmd.hasOption("o")) {
        rulesSelection = true;
        String ontDirPath = cmd.getOptionValue("o");
        ontDir = new File(ontDirPath);
        if (!ontDir.isDirectory()) {
            logger.warn(ontDirPath + " is not a valid directory path.");
            System.exit(0);
        }
    }
    if (!cmd.hasOption("r")) {
        logger.info("You must specify a path for inference rules directory !");
        System.exit(0);
    } else if (rulesSelection) {

    }

    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    String rulesDirPath = cmd.getOptionValue("r");
    rulesDir = new File(rulesDirPath);
    if (!rulesDir.isDirectory()) {
        logger.warn(rulesDirPath + " is not a valid directory path.");
        System.exit(0);
    }

    /////////////////
    Graph graph = Graph.create();
    QueryProcessDQP execDQP = QueryProcessDQP.create(graph);
    for (String url : endpoints) {
        try {
            execDQP.addRemote(new URL(url), WSImplem.REST);
        } catch (MalformedURLException ex) {
            logger.error(url + " is not a well-formed URL");
            System.exit(1);
        }
    }

    // Local rules graph initialization
    Graph rulesG = Graph.create();
    Load ld = Load.create(rulesG);

    if (rulesSelection) {
        // Ontology loading
        if (ontDir.isDirectory()) {
            for (File o : ontDir.listFiles()) {
                logger.info("Loading " + o.getAbsolutePath());
                ld.load(o.getAbsolutePath());
            }
        }
    }

    // Rules loading
    if (rulesDir.isDirectory()) {
        for (File r : rulesDir.listFiles()) {
            logger.info("Loading " + r.getAbsolutePath());
            ld.load(r.getAbsolutePath());
        }
    }

    // Rule engine initialization
    RuleEngine ruleEngine = RuleEngine.create(graph);
    ruleEngine.set(execDQP);

    StopWatch sw = new StopWatch();
    logger.info("Federated graph size : " + graph.size());
    logger.info("Rules graph size : " + rulesG.size());

    // Rule selection
    logger.info("Rules selection");
    QueryProcess localKgram = QueryProcess.create(rulesG);
    ArrayList<String> applicableRules = new ArrayList<String>();
    sw.start();
    String rulesSelQuery = "";
    if (rulesSelection) {
        rulesSelQuery = pertinentRulesQuery;
    } else {
        rulesSelQuery = allRulesQuery;
    }
    Mappings maps = localKgram.query(rulesSelQuery);
    logger.info("Rules selected in " + sw.getTime() + " ms");
    logger.info("Applicable rules : " + maps.size());

    // Selected rule loading
    for (Mapping map : maps) {
        IDatatype dt = (IDatatype) map.getValue("?res");
        String rule = dt.getLabel();
        //loading rule in the rule engine
        //            logger.info("Adding rule : " + rule);
        applicableRules.add(rule);
        ruleEngine.addRule(rule);
    }

    // Rules application on distributed sparql endpoints
    logger.info("Rules application (" + applicableRules.size() + " rules)");
    ExecutorService threadPool = Executors.newCachedThreadPool();
    RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine);
    sw.reset();
    sw.start();

    //        ruleEngine.process();
    threadPool.execute(ruleThread);
    threadPool.shutdown();

    //monitoring loop
    while (!threadPool.isTerminated()) {
        System.out.println("******************************");
        System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter,
                QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));
        System.out.println("Rule engine running for " + sw.getTime() + " ms");
        System.out.println("Federated graph size : " + graph.size());
        Thread.sleep(10000);
    }

    logger.info("Federated graph size : " + graph.size());
    logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter,
            QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));

    ///////////// Query file processing
    //        StringBuffer fileData = new StringBuffer(1000);
    //        BufferedReader reader = null;
    //        try {
    //            reader = new BufferedReader(new FileReader(queryPath));
    //        } catch (FileNotFoundException ex) {
    //             logger.error("Query file "+queryPath+" not found !");
    //             System.exit(1);
    //        }
    //        char[] buf = new char[1024];
    //        int numRead = 0;
    //        try {
    //            while ((numRead = reader.read(buf)) != -1) {
    //                String readData = String.valueOf(buf, 0, numRead);
    //                fileData.append(readData);
    //                buf = new char[1024];
    //            }
    //            reader.close();
    //        } catch (IOException ex) {
    //           logger.error("Error while reading query file "+queryPath);
    //           System.exit(1);
    //        }
    //
    //        String sparqlQuery = fileData.toString();
    //
    //        Query q = exec.compile(sparqlQuery,null);
    //        System.out.println(q);
    //        
    //        StopWatch sw = new StopWatch();
    //        sw.start();
    //        Mappings map = exec.query(sparqlQuery);
    //        int dqpSize = map.size();
    //        System.out.println("--------");
    //        long time = sw.getTime();
    //        System.out.println(time + " " + dqpSize);
}