Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Multiple Threads in certain time for Java

What is the best way to create 500.000 threads in 5 seconds. (Runnable) I created for loop but it takes lots of time. For example;

startTime = System.currentTimeMills();

for (int i=0;i<500.000; i++){
 // create thread
  thread.start();
}

resultTime = (System.currentTimeMills() - startTime);

So the resultTime is bigger than 5 seconds. I know it depends on my hardware and os configuration but i just want to know what is the best way to create multiple threads in certain time?

Thanks.

like image 267
user1557009 Avatar asked Jun 29 '26 04:06

user1557009


2 Answers

I really can't imagine this is a good idea. Each thread takes a reasonable amount of resource (by default, 512k of heap for each thread) and so even if you create all your threads, your JVM will be fighting for resources.

If you have a requirement for 500,000 work units, I think you're better off creating these as Runnables (and not all at once!) and passing them to a ThreadPool tuned to your environment.machine (e.g. a naive/simple tuning would be one thread per CPU)

like image 102
Brian Agnew Avatar answered Jul 01 '26 16:07

Brian Agnew


The fastest way to create many tasks is to use an ExecutorService

int processors = Runtime.getRuntime().availableProcessors();
ExecutorService es = Executors.newFixedThreadPool(processors);

long start = System.nanoTime();
int tasks = 500 * 1000;
for (int i = 0; i < tasks; i++) {
    es.execute(new Runnable() {
        @Override
        public void run() {
            // do something.
        }
    });
}
long time = System.nanoTime() - start;
System.out.printf("Took %.1f ms to create/submit %,d tasks%n", time / 1e6, tasks);
es.shutdown();

prints

Took 143.6 ms to create/submit 500,000 tasks
like image 23
Peter Lawrey Avatar answered Jul 01 '26 18:07

Peter Lawrey