Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how many threads to run in java?

I had this brilliant idea to speed up the time needed for generating 36 files: use 36 threads!! Unfortunately if I start one connection (one j2ssh connection object) with 36 threads/sessions, everything lags way more than if I execute each thread at a time.
Now if I try to create 36 new connections (36 j2ssh connection objects) then each thread has a separate connection to server, either i get out of memory exception (somehow the program still runs, and successfully ends its work, slower than the time when I execute one thread after another).

So what to do? how to find the optimal thread number I should use? because Thread.activeCount() is 3 before starting mine 36 threads?! i'm using Lenovo laptop Intel core i5.

like image 207
user615927 Avatar asked Aug 24 '26 02:08

user615927


1 Answers

You could narrow it down to a more reasonable number of threads with an ExecutorService. You probably want to use something near the number of processor cores available, e.g:

int threads = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(threads);
for (int i = 0; i < 36; i++) {
    service.execute(new Runnable() {
        public void run() {
            // do what you need per file here
        }
    });
}
service.shutdown();
like image 102
WhiteFang34 Avatar answered Aug 25 '26 15:08

WhiteFang34