multithreading - Why is my code slower using multiple threads in Java? -


so have program runs bunch of different calculations returns result when calculations done.

originally code synchronous following:

public class myapplication{      public static void main(string[] args) {         docalculation(1);         docalculation(2);         docalculation(3);         docalculation(4);         docalculation(5);         docalculation(6);         docalculation(7);         docalculation(8);          /* print result */     } } 

i thought more efficient run these calculations in new threads have like,

public class myapplication{     public static void main(string[] args) {         list<thread> threads = new arraylist<thread>();         threads.add(docalculation(1));         threads.add(docalculation(2));         threads.add(docalculation(3));         threads.add(docalculation(4));         threads.add(docalculation(5));         threads.add(docalculation(6));         threads.add(docalculation(7));         threads.add(docalculation(8));          for(thread t : threads){             if(t.isalive()){                 try{                     t.join();                 } catch(interruptedexception e) {                     system.out.println("error calculating fitness");                 }             }         }          /* print result */     } } 

i'm sorry, i'm complete beginner threads. if had guess i'd assume i'm spawn off 2 many new threads (there 50 calculations in application), advise appreciated!

for optimal parallelism number of threads must not exceed number of cpu cores available, beyond creates overhead context switching. also, threads expensive create letting thread die after completing 1 calculation big waste. instead should rely on excellent support parallelism comes java library.

my advice use java 8 streams api , formulate problem parallel stream, such as

intstream.range(1, 9).map(this::docalculation).parallel().collect(collectors.tolist()); 

this executed on common forkjoinpool, default sized according number of cpu cores.

i assume overall work parallelizing takes substantial time on single core (at least several milliseconds) , no i/o involved because basic preconditions parallelization worth it. if there not enough work do, overhead of task handoff threads , result collection eat away advantage of parallel processing. if i/o, blocking occur, occupying thread while cpu sits idle.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -