【问题标题】:How to execute multiple sql query parallel in java如何在java中并行执行多个sql查询
【发布时间】:2018-01-20 06:00:22
【问题描述】:

我有 3 个方法返回一个结果列表,我的 sql 查询在每个方法中执行并返回一个结果列表。我想并行执行所有 3 个方法,这样它就不会等待一个又一个完成。我看到了一篇 stachoverflow 帖子,但它不起作用。 该链接是 [How to execute multiple queries in parallel instead of sequentially? [Execute multiple queries in parallel via Streams

我想使用 java 8 特性来解决。 但是上面的链接如何调用多个方法请告诉我。

【问题讨论】:

  • 链接中的答案有什么错误?

标签: concurrency parallel-processing java-8


【解决方案1】:

Execute multiple queries in parallel via Streams 适合您的任务。这是一个演示它的示例代码:

public static void main(String[] args) {
    // Create Stream of tasks:
    Stream<Supplier<List<String>>> tasks = Stream.of(
            () -> getServerListFromDB(),
            () -> getAppListFromDB(),
            () -> getUserFromDB());

    List<List<String>> lists = tasks
            // Supply all the tasks for execution and collect CompletableFutures
            .map(CompletableFuture::supplyAsync).collect(Collectors.toList())
            // Join all the CompletableFutures to gather the results
            .stream()
            .map(CompletableFuture::join).collect(Collectors.toList());
    System.out.println(lists);
}

private static List<String> getUserFromDB() {
    try {
        TimeUnit.SECONDS.sleep((long) (Math.random() * 3));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName() + " getUser");
    return Arrays.asList("User1", "User2", "User3");
}

private static List<String> getAppListFromDB() {
    try {
        TimeUnit.SECONDS.sleep((long) (Math.random() * 3));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(Thread.currentThread().getName() + " getAppList");
    return Arrays.asList("App1", "App2", "App3");
}

private static List<String> getServerListFromDB() {
    try {
        TimeUnit.SECONDS.sleep((long) (Math.random() * 3));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(Thread.currentThread().getName() + " getServer");
    return Arrays.asList("Server1", "Server2", "Server3");
}

输出是:

ForkJoinPool.commonPool-worker-1 getServer
ForkJoinPool.commonPool-worker-3 getUser
ForkJoinPool.commonPool-worker-2 getAppList
[[Server1, Server2, Server3], [App1, App2, App3], [User1, User2, User3]]

您可以看到使用了默认的 ForkJoinPool.commonPool,并且每个 get* 方法都是从该池中的单独线程执行的。您只需要在这些 get* 方法中运行 SQL 查询

【讨论】:

  • .collect(Collectors.toList()).stream() 可以而且应该省略
猜你喜欢
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多