Grails, GPars and data persistence
Asked Answered
C

2

10

Something is not getting flushed. A simplified example of what's happening:

def testDemo() {
    def person = new Person(...)
    person.save(flush: true)

    println "Number of people after save: " + Person.all.size()

    def dummyList = [1, 2, 3, 4, 5]

    GParsPool.withPool { num ->
        println "Number of people after withPool: " + Person.all.size()
        dummyList.eachParallel {
            println "Number of people after eachParallel " + Person.all.size()
            Person.withTransaction {
            ...

This outputs:

Number of people after save: 1
Number of people after withPool: 1
Number of people after eachParallel: 0

I don't understand if I have to do something with Session and Transaction to make the data persist or if this is a bug in GPars. What is going on here at the underlying hibernate level?

I want the recently created Person to be visible within the parallel closure.

Clay answered 29/12, 2012 at 6:9 Comment(1)
how did you overcome this? @ClayDallasdalli
U
12

Gpars is a multi-threaded tool and the hibernate session injected in your domain class isn't thread-safe.

Try using these methods or invoking SessionFactory directly:

  • withNewSession
  • withNewTransaction

Beware that opening a session for each thread can be extremely costly and might flood your database with new connections.

Unsocial answered 31/12, 2012 at 2:21 Comment(1)
+1 "session ... isn't thread-safe" Thanks! This answers why I needed a lock in a place that should have been safe from concurrency. I am using withNewSession instead of withTransaction.Clay
C
1

I recently have a similar problem. As I understood, it seems to be that the threads could not bind the hibernate session, I can't get it to work either. If you don't really need it, try to write code dealing with persistence out of GPars. That is the way I get it to work.

Canasta answered 30/12, 2012 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.