I've come across something a little peculiar - using the program given below, I can create j number of threads which start and print their counter value (whichever thread number they are given), then count to a billion, then stop and print their counter value as well as the elapsed time it took for the thread to complete its execution for the part I care about. Here is my code:
public static void main(String []args){
for(int j=0;j<200;j++){
final int x = j;
new Thread(()->{
System.out.println("start " + x);
try{Thread.sleep(500);}catch(Exception e){}//this lets all the threads be created before running any calculations
long a = System.nanoTime();
for(int i=0;i<1000000000;i++){
}
long b = System.nanoTime();
System.out.println("stop " + x + " : " + ((b-a))/1000000000.0);//outputs time in seconds
}).start();
}
}
What's odd is that when j, the number of created threads, is low (usually <50), the output looks to be what I would consider to be normal - here's an example with 6 threads:
start 3
start 1
start 4
start 5
start 0
start 2
stop 5 : 0.0035043
stop 1 : 0.0034917
stop 4 : 0.0035097
stop 2 : 0.004224
stop 0 : 0.0025082
stop 3 : 0.004472
Notice how all the times are larger than 0.003. However, when many threads are created, there are "normal" times that show up (similar to the times above), but a large portion tend to gives times in the order of 10^-5 - here is a snippet of the output:
stop 49 : 1.09E-5
stop 13 : 2.81E-5
stop 2 : 1.98E-5
stop 18 : 6.4E-6
stop 19 : 0.0616381
stop 7 : 0.0575055
stop 14 : 0.0648309
My question is - how can it be possible that, as you add more threads, their execution times become shorter? Is it not logical that as more threads to execute are added they should all, on average, take longer? I'm mostly certain this isn't a volatility issue - each thread should only be able to touch the data relevant to itself.
It might be important to note that I'm running this on a computer with a 4 GHz hexa-core processor and 17+ GB unused RAM