开发者

How to determine max number of threads avialable in Java-VM?

I want to determine the max number of threads I am able to cr开发者_开发技巧eate for my sort algoritm. I want to use java.lang.Runtime for that.

I want to count the current thread amount and stop creating new threads when the limit is reached.


The max number of threads for a JVM is generally somewhere in the thousands. If you're using multiple threads to optimize a computational algorithm you don't really want more than the number of processors in the system its run on. Use Runtime.getRuntime().availableProcessors() to find out.


I'd suggest you look at the problem from a slightly different angle...

what I mean is that if you're asking

"what's the maximum number of threads I can create and use for task x?"

and you're asking that because you think the most threads you use the better, you could instead ask

"how many threads would I need to complete x most efficiently?"

its very unlikely that task x will perform better with thousands of threads on a dual core machine for example. As a general guide for example, for CPU bound tasks (which a sort algorithm probably is), the optimal number of threads is

threads = number of CPUs + 1

see How to find out the optimal amount of threads?

The actual maximum number of threads depends on the OS and JVM along with how much memory is configured for use within the JVM. Creating a new thread takes some OS memory but not Java' heap memory. This means that if you create thousands of threads, you might run out of memory which you can't bump up using -Xmx. In fact, the less Java heap memory you allocate, the more native memory is available and so the more threads you can create.

See this article and the comment to get a feel for how you can work out the max with pen and paper.

Having said all that, if you want to use an unlimited number of threads in your application, you can use the `Executors.newCachedThreadPool()' which will create a pool of threads, creating as many as are needed. I don't recommend using this type of pool for everyday usage, but its related to your original question.

Hope that helps.


You can see how many threads you have by attaching visualvm to your process. I recommend version 1.3.2 with all the plugins downloaded.

I'd also recommend using Spring and its Executor pools. It's a great way to be able to configure the size of the thread pool.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜