<p>Any ideas how to determine the number of active threads currently running in an <a href="https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html" rel="noreferrer"><code>ExecutorService</code></a>?</p>

[{'answer_id': 80809, 'author': 'Daan', 'author_id': 197, 'author_profile': 'https://Stackoverflow.com/users/197', 'pm_score': 7, 'selected': True, 'text': '<p>Use a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="noreferrer">ThreadPoolExecutor</a> implementation and call <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getActiveCount()" rel="noreferrer">getActiveCount()</a> on it:</p>\n\n<pre><code>int getActiveCount() \n// Returns the approximate number of threads that are actively executing tasks.\n</code></pre>\n\n<p>The ExecutorService interface does not provide a method for that, it depends on the implementation.</p>\n'}, {'answer_id': 80814, 'author': 'Javaxpert', 'author_id': 15241, 'author_profile': 'https://Stackoverflow.com/users/15241', 'pm_score': -1, 'selected': False, 'text': '<p>Place a static volatile counter on the thread which is updated whenever the thread is activated and deactivated.\nAlso, see the API.</p>\n'}, {'answer_id': 80828, 'author': 'Arno', 'author_id': 13685, 'author_profile': 'https://Stackoverflow.com/users/13685', 'pm_score': 5, 'selected': False, 'text': '<p>Check the sourcecode for <code>Executors.newFixedThreadPool()</code>:</p>\n\n<pre><code>return new ThreadPoolExecutor(nThreads, nThreads,\n                              0L, TimeUnit.MILLISECONDS,\n                              new LinkedBlockingQueue&lt;Runnable&gt;());\n</code></pre>\n\n<p>ThreadPoolExecutor has a getActiveCount() method. So you might either cast the ExecutorService to ThreadPoolExecutor, or use the above code directly to obtain one. You can then invoke <code>getActiveCount()</code>.</p>\n'}, {'answer_id': 80874, 'author': 'Dave Cheney', 'author_id': 6449, 'author_profile': 'https://Stackoverflow.com/users/6449', 'pm_score': 3, 'selected': False, 'text': '<p>The ExecutorService interface does not define a method to examine the number of worker threads in the pool, as this is an implementation detail</p>\n\n<pre><code>public int getPoolSize()\nReturns the current number of threads in the pool.\n</code></pre>\n\n<p>Is available on the ThreadPoolExecutor class</p>\n\n<pre>\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\n\npublic class PoolSize {\n\n    public static void main(String[] args) {\n        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());\n        System.out.println(executor.getPoolSize());\n    }\n}\n</pre>\n\n<p>But this requires you to explicitly create the ThreadPoolExecutor, rather than using the Executors factory which returns ExecutorService objects. You could always create your own factory that returned ThreadPoolExecutors, but you would still be left with the bad form of using the concrete type, not its interface.</p>\n\n<p>One possibility would be to provide your own ThreadFactory which creates threads in a known thread group, which you can then count</p>\n\n<pre>\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ThreadFactory;\n\n\npublic class PoolSize2 {\n\n    public static void main(String[] args) {\n        final ThreadGroup threadGroup = new ThreadGroup("workers");\n\n        ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {\n            public Thread newThread(Runnable r) {\n                return new Thread(threadGroup, r);\n            }\n        });\n\n        System.out.println(threadGroup.activeCount());\n    }\n}\n</pre>\n'}, {'answer_id': 18563922, 'author': 'andyroid', 'author_id': 1546403, 'author_profile': 'https://Stackoverflow.com/users/1546403', 'pm_score': 5, 'selected': False, 'text': '<p>Assuming <code>pool</code> is the name of the ExecutorService instance:</p>\n\n<pre><code>if (pool instanceof ThreadPoolExecutor) {\n    System.out.println(\n        "Pool size is now " +\n        ((ThreadPoolExecutor) pool).getActiveCount()\n    );\n}\n</code></pre>\n'}, {'answer_id': 38182852, 'author': 'Ankit Katiyar', 'author_id': 3373597, 'author_profile': 'https://Stackoverflow.com/users/3373597', 'pm_score': 2, 'selected': False, 'text': '<p>I had same issue so created a simple Runnable to trace a ExecutorService instance. </p>\n\n<pre><code>import java.util.concurrent.ExecutorService;\nimport java.util.concurrent.ThreadPoolExecutor;\n\npublic class ExecutorServiceAnalyzer implements Runnable\n{\n    private final ThreadPoolExecutor threadPoolExecutor;\n    private final int timeDiff;\n\n    public ExecutorServiceAnalyzer(ExecutorService executorService, int timeDiff)\n    {\n        this.timeDiff = timeDiff;\n        if (executorService instanceof ThreadPoolExecutor)\n        {\n            threadPoolExecutor = (ThreadPoolExecutor) executorService;\n        }\n        else\n        {\n            threadPoolExecutor = null;\n            System.out.println("This executor doesn\'t support ThreadPoolExecutor ");\n        }\n\n    }\n\n    @Override\n    public void run()\n    {\n        if (threadPoolExecutor != null)\n        {\n            do\n            {\n                System.out.println("#### Thread Report:: Active:" + threadPoolExecutor.getActiveCount() + " Pool: "\n                        + threadPoolExecutor.getPoolSize() + " MaxPool: " + threadPoolExecutor.getMaximumPoolSize()\n                        + " ####");\n                try\n                {\n                    Thread.sleep(timeDiff);\n                }\n                catch (Exception e)\n                {\n                }\n            } while (threadPoolExecutor.getActiveCount() &gt; 1);\n            System.out.println("##### Terminating as only 1 thread is active ######");\n        }\n\n    }\n}\n</code></pre>\n\n<p>You can simply use this with your executor to get states of ThreadPool </p>\n\n<p>Ex </p>\n\n<pre><code>ExecutorService executorService = Executors.newFixedThreadPool(4);\n    executorService.execute(new ExecutorServiceAnalyzer(executorService, 1000));\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/80787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8441/']