CompletableFuture,主从不退出

时间:2019-06-05 16:18:56

标签: java java-8 completable-future

我正在学习Java 8,以及“ CompletableFuture”的更多信息。 跟随这个有趣的教程: https://www.callicoder.com/java-8-completablefuture-tutorial/

我编写了以下Java类:

package parallels;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;




public class Test {
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0";
    private static final Executor executor = Executors.newFixedThreadPool(100);

    public static void main(String[] args) {

        List<String> webPageLinks= new ArrayList<String>();
        for (int i=0;i<30;i++) {
            webPageLinks.add("http://jsonplaceholder.typicode.com/todos/1");
        }

        // Download contents of all the web pages asynchronously
        List<CompletableFuture<String>> pageContentFutures = webPageLinks.stream()
                .map(webPageLink -> downloadWebPage(webPageLink))
                .collect(Collectors.toList());


        // Create a combined Future using allOf()
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                pageContentFutures.toArray(new CompletableFuture[pageContentFutures.size()])
                );


        // When all the Futures are completed, call `future.join()` to get their results and collect the results in a list -
        CompletableFuture<List<String>> allPageContentsFuture = allFutures.thenApply(v -> {
            return pageContentFutures.stream()
                    .map(pageContentFuture -> pageContentFuture.join())
                    .collect(Collectors.toList());
        });


    }



    private static CompletableFuture<String> downloadWebPage(String pageLink) {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> getRequest(pageLink),executor);
        return completableFuture;
    } 

    public static String getRequest(String url) {
        System.out.println("getRequest");
        String resp =null;
        try {
            ResteasyClient client = new ResteasyClientBuilder().build();
            ResteasyWebTarget target = client.target(url);
            target.register((ClientRequestFilter) requestContext -> {
                requestContext.getHeaders().add("User-Agent",USER_AGENT);
            });
            Response response = target.request().get();
            resp= response.readEntity(String.class);
            System.out.println(resp);
            response.close();  
            client.close();

            System.out.println("End getRequest");
        }catch(Throwable t) {
            t.printStackTrace();
        }




        return resp;

    }



}

(要运行该代码,您需要“ resteasy-client”库)

但是我不明白为什么即使收集了所有响应后main方法也不会终止...

我错过了什么吗? 有什么“完整”方法可以在任何地方调用,如果可以的话,可以在哪里调用?

1 个答案:

答案 0 :(得分:3)

您的主要方法完成了,但是当您创建了其他仍处于活动状态的线程时,程序将继续运行。最好的解决方案是在将所有任务提交给它之后,在您的ExecutorService上调用shutdown

或者,您可以创建一个使用daemon线程(请参阅Thread documentation)的ExecutorService或带有allowCoreThreadTimeout(true)的ThreadPoolExecutor,或者只需在您的结尾处调用System.exit主要方法。