views:

36

answers:

2

Hi, I have a grails app and I need to trigger an cpu-intensive process. I'm thinking in creating a service that spawns multiple threads that do the same calculations but with random data to compare the results later on. Is it safe to do it this way ? Any recommendations / experiences ?

Thanks.

+1  A: 

<plug>

As it happens, I'm currently reviewing chapter 17 of the second edition of Groovy in Action right now (as in I have the Word document open, and I'm editing it whenever I'm not posting here). That chapter covers concurrency in Groovy in general - it doesn't explicitly mention Grails, but I doubt that that has much impact on what you might want to use. Chapter 17 is already available in the early access "MEAP" edition...

</plug>

Anyway, I don't have any direct experience of concurrency in Groovy myself, but it sounds like you should be looking at GPars.

Jon Skeet
+2  A: 

The biggest problem you'll likely have is that any threads you create won't automatically have a hibernate session attached to them. So if you need to do anything with your domain, you'll need to wire up stuff manually. I looked into it a while ago and it was doable, but I ended up going another way so don't have a finished example to talk about.

I think that there were also a couple of plugins out there, like the Background Thread plugin that will spawn a thread for you and attach the appropriate hibernate stuff. I'm not sure that the plugin is still maintained though so it's possible it won't work on 1.3 or later.

You might also be able to instantiate a valid transaction in your thread by using withTransactionlink text:

MyDomain.withTransaction { status ->
    // GORM stuff that needs a valid transaction
}

Note that each thread would then have it's own transaction and that it wouldn't participate in the same transaction as the other threads (so you wouldn't be able to roll everything back if one thread fails).

Ted Naleid