Wednesday, January 27, 2010

Asynchronous Groovy

In my previous post, i showed how simple asynchronous code in Spring 3 is. I wanted to see what it takes to write the same code in Groovy. Well, it is quite straightforward, using the GPARS library. The docs there show it to be quite powerful, but to be loyal to our simple example, here is the code:



   1: Asynchronizer.withAsynchronizer(4) {ExecutorService service ->



   2:       (0..9).each { num->



   3:         service.submit({



   4:         Thread.sleep(2000);



   5:         println("Running for ${num} thread ${Thread.currentThread()}")}as Runnable)



   6:       }



   7: }



See how you specify the number of threads in the parameter to the closure withAsynchronizer.
There are lots more examples at the GPARS site.

No comments:

Post a Comment