Reputation: 32321
I am working on a existing code, where I found this piece of code in one of the class.
The code is using ExecutorService
, instead of doing MyThread.start
.
Please tell me why to use ExecutorService
instead of Thread.start
.
protected static ExecutorService executor = Executors.newFixedThreadPool(25);
while (!reader.isEOF()) {
String line = reader.readLine();
lineCount++;
if ((lineCount > 1) && (line != null)) {
MyThread t = new MyThread(line, lineCount);
executor.execute(t);
}
}
Upvotes: 4
Views: 1210
Reputation: 328629
I suppose MyThread
extends Thread
and Thread
implements Runnable
. What you are doing in that code is submitting a Runnable to the executor, which will execute it in one of its 25 threads.
The main difference between that and starting the threads directly with myThread.start()
is that if you have 10k lines, this could start 10k threads concurrently, which would probably exhaust your resources pretty quickly.
With the executor as it is defined, no more than 25 threads will run at any time, so if a task is submitted while all 25 threads are already in use, it will wait until one of the threads becomes available again and run in that thread.
Upvotes: 5