并发访问ExecutorService

Awa*_*iru 2 java multithreading java.util.concurrent

考虑以下服务类别:

//Singleton service
public class InquiryService{

    private final ExecutorService es = Executors. newSingleThreadExecutor();
    private final CustomerService cs = new CustomerServiceImpl();

    public String process(){

          //Asynchronous calls to get info from CustomerService
          Future<String> result = es.submit(()->{return cs.getCustomer()});

          //Query database
          //Perform logic et all

          String customerName = result.submit.get();

          //continue processing.
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的服务类具有一个ExecutorServiceas字段。如果说在process方法上有100个并发请求,那么剩下的(100-1)个请求是否需要等待线程可用性?

如何解决请求等待?我可以想到的一种选择是ExecutorServiceprocess方法内实例化,使用和关闭。但是,线程池不是要重用吗?

另一个选项将作为运行new Thread(new FutureTask<>(() -> {return cs.getCustomer()}))。哪一种是正确的方法?

更新:-

根据评论和答案,ExecutorService要重用和频繁Thread创建新内容的成本很高。因此,另一个选择是依次运行服务调用。

Moh*_*s A 5

您的服务singleton意味着在应用程序的整个运行期间仅存在一个实例(如果实现正确!)。因此,有效地,您可以ExecutorService处理newFixedThreadPool(1)

剩余的(100-1)请求是否需要等待线程可用性?

哦,是的,您的所有其他100-1请求都必须等待,因为第一个请求已在线程池中存在的线程中执行。由于线程池的大小是固定的,因此它永远无法增长以处理其他请求。

如何解决请求等待?

您需要在线程池中使用更多线程来执行任务。

我想到的一种选择是在过程方法中实例化,使用和关闭ExecutorService

这真是个坏主意。创建和销毁Thread所花费的时间过多。更多关于此这里。那是使用的整个想法ThreadPool

另一个选项将作为新线程运行(新FutureTask <>((()-> {return cs.getCustomer()}))

构造一个new Thread()。阅读我的前一点。

那么,什么是对的!

一种方法是访问Executors.newFixedThreadPool(10),以便(90-10)个请求等待。可以吗 也许您正在寻找newCachedThreadPool

警告:此外,如果适用,请阅读有关ThreadLocal在中使用的副作用ThreadPool