Reputation: 459
In multithreading (Executor framework), the sum total of all time-prints within x() method is not matching to the total time printed by doPerform. And this difference keeps on growing with increasing number of threads in threadpool (goes upto 20 secs). Can someone please figure out why? And is there any way to decrease time taken to return from x method?
I have tested it with:
a) 500 submissions to executor (poolsize =100)
b) 500 submissions to executor (poolsize =300)
c) 300 submissions to executor (poolsize =100)
public void x() {
long startTime = System.currentTimeMillis();
for (long l = 0; l <= 10000000; l++) {
if (l % 1000000 == 0) {
System.out.println("Thread id: "
+ Thread.currentThread().getId() + "\t"
+ (System.currentTimeMillis() - startTime));
startTime = System.currentTimeMillis();
}
}
}
public void doPerform() {
long startTime = System.currentTimeMillis();
x();
System.out.println("Thread id: " + Thread.currentThread().getId()
+ "\t" + (System.currentTimeMillis() - startTime));
}
Upvotes: 1
Views: 277
Reputation: 692073
That's expected. You have 100 or 300 parallel threads being executed, and only 1, 2 or 4 cores to execute them all (unless you're running this on a giant super computer). This means that each thread is assigned some CPU time, then some other thread, then some other thread, etc. giving the illusion of parallel execution. But in reality, instructions of various threads are interlaced and executed sequentially.
So, you could have a thread A's startTime
computation in doPerform()
executed, and then the thread could be replaced by several other ones one on the CPU. A number of milliseconds could elapse before the thread scheduler reassigns A to a CPU and the startTime
computation in x()
is executed.
Upvotes: 1