HJW
HJW

Reputation: 23443

when spawning threads, how do I throttle the maximum number possible?

How do I spawn threads to the maximum number possible assuming that each thread may take different time to complete. The idea is to spawn the maximum number of threads possible while not causing any to die.

E.g. While (spawnable) spawn more threads;

I am trying to spawn threads to make calls to ejb, I wish to spawn the maximum number possible to simulate a load while not causing the threads to go into out of memory exception.

Upvotes: 1

Views: 481

Answers (3)

Pablo Fernandez
Pablo Fernandez

Reputation: 105258

The Executor framework has been cited here, and it's a wonderful tool indeed (Already +1'ed that answer).

But I believe what the OP wants is a Executors.newCachedThreadPool().

From the docs:

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available

More on executors here

Upvotes: 1

SJuan76
SJuan76

Reputation: 24895

There is no fixed answer. You need to tune the number of threads to your host capabilities.

In response to the memory issue, it is not only a matter of how many threads are there but also of what they do. It is not the same if they perform simple calls or have to deal with huge arrays.

Relative for performance, and supposing that your host is dedicated, a value of one thread per core is a minimum value. Given that they are going to call a remote system most of these threads will spend a time idle; depending of the proportion of idle time you can spawn more or less.

In essence, chech your host performance and tune your thread number in consequence.

Upvotes: 2

Ryan Stewart
Ryan Stewart

Reputation: 128919

Executors.newFixedThreadPool() or for finer control, create your own ThreadPoolExecutor.

Upvotes: 6

Related Questions