如何使用Java服务限制线程数

时间:2018-07-27 04:41:39

标签: java multithreading threadpool executorservice futuretask

我的要求是限制在任何时间点使用我的服务的线程数。执行器服务在这里没有帮助我,因为我的问题空间几乎没有什么不同。让我用一个例子来解释。

我公开了一种可完成一项工作的REST API。运行中,我的控制器调用服务之一来执行作业。但是我必须确保只有“ n”个线程才能访问该服务。这意味着线程/ API访问将持续增长,但是在某些地方,如果'n'个线程已经在使用该服务,我必须让它们处于等待状态。在执行结束时,我应该从服务获得响应,并返回到端点,然后再返回到客户端。

如果我使用FutureTask和callable,如何以及在哪里编写.get()方法?因为我的线程数量将不断增长并且本质上会不断变化。

希望问题陈述清楚,如果需要更多说明,请告诉我。

2 个答案:

答案 0 :(得分:1)

如果仅想限制可以访问您的服务的最大线程数,则可以使用Bounded Semaphore并提供最大允许数量。 这是示例代码(假设您的服务是单例的):-

public class SampleService {
    private Semaphore semaphore = new Semaphore(n, true);

    public void someMothod() {
        try {
            semaphore.acquire();

            // execute the task

        } catch (InterruptedException e) {
        } finally {
            semaphore.release();
        }

    }
}

您必须确保仅创建一个信号量实例。如果您可以在应用程序中拥有多个服务实例,则将信号量设为静态。

private static Semaphore semaphore = new Semaphore(n, true);

答案 1 :(得分:0)

您可以为此使用ExecutorCompletionService。 只需创建一个固定的线程数如下所示的ExecutorService

LinkedList<E>

现在使用此ExecutorService创建一个ExecutorCompletionService。

ExecutorService pool = Executors.newFixedThreadPool(5);

然后,在提交任务后,您可以进行迭代并获得未来以及未来的工作成果。当您使用仅从ExecutorService返回的Future时,这不会阻止线程完成操作。

ExecutorCompletionService completionService = new ExecutorCompletionService(pool);