MeIr
MeIr

Reputation: 7326

Grails Quartz & threads inside service

I have a question about Quartz and running threads inside Service class.

I got my previous question answered: Grails background process, however I have another issue.

Setup: I have a Job that is setup to run a Service and it works perfectly. However inside a Service class I have an algorithm that can run in parallel.

Issue: Typically I would setup code to run in parallel in the following very simple way:

Item.each {
   Thread.start {
      do some calculations here    
      write to DB
   }
}

However, since my code need to write into DB and I need to leverage domain classes and at that point my code brakes. Hibernate complains that threads don't have access to something.

I am not sure why I can't use threads inside Service class and leverage domain class. Can someone help me with this dilemma? Do I need to create threads in a special way? May be I shouldn't be creating threads in Service class (since Service class seem to be running inside threads )? Do I need to move my code into Job class?

Please help.

Thank you.

Upvotes: 1

Views: 1258

Answers (1)

schmolly159
schmolly159

Reputation: 3881

The new Threads won't have a Hibernate Session bound to them by default. To attach a Hibernate Session, try the following:

Item.each {
    Thread.start {
        Item.withTransaction {
            do some calculations here    
            write to DB
        }
    }
}

You could also look into GPars for an easy to use parallelization framework.

Upvotes: 1

Related Questions