java - @Async prevent a thread to continue until other thread have finished -


i have application number of times needs calculated. calculation function has annotation @async (from spring framework), makes possible run these calculations on 4 threads. problem need 40000 of these calculations , want know time between start , end of calculations, see time before , after for-loop calls calculation functions. calculations put in queue, loop finishes , time 1 second, while takes couple of hours calculations complete. i've tried setting max queue size 100 (also reduce memory usage) no solution since i'll miss last 100 calculations in total time takes. there way pause executing code after loop until threads have finished doing work, still being able use @async annotation?

this code illustrates same problem:

executing class:

public class foo {     public void executeblaalotoftimes() {         long before = system.currenttimemillis();          (int = 0; i<40000; i++) {             executebla();         }          long after = system.currenttimemillis();           system.out.println("time took lot of bla execute: " + (after - before) / 1000.0 + " seconds.");     } } 

and class performs calculations:

@service public class bar {     @async     public void executebla() {         system.out.println("bla!");     } } 

this result in following output (assuming code in foo executes infinitely fast):

 time took lot of bla execute: 0.0 seconds. bla! bla! bla! bla! . . . etc 

if need wait executions finish, can return future return value, e.g.

@async public future<void> executebla() {     system.out.println("bla!");     return new asyncresult<void>(null); } 

this artificial, since there's no actual value being returned, still allow calling code wait executions finish:

public void executeblaalotoftimes() {     long before = system.currenttimemillis();      collection<future<void>> futures = new arraylist<future<void>>();      (int = 0; i<40000; i++) {         futures.add(executebla());     }      (future<void> future : futures) {         future.get();     }      long after = system.currenttimemillis();       system.out.println("time took lot of bla execute: " + (after - before) / 1000.0 + " seconds."); } 

here, first loop fires off async tasks , stores futures in list. seconds loop iterates on futures, waiting each 1 finish.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -