JPA atomic query/save for multithreaded app

Posted by TofuBeer on Stack Overflow See other posts from Stack Overflow or by TofuBeer
Published on 2010-06-07T19:27:59Z Indexed on 2010/06/07 19:32 UTC
Read the original article Hit count: 208

Filed under:
|

I am in the midst of changing my JPA code around to make use of threads. I have a separate entity manager and transaction for each thread.

What I used to have (for the single threaded environment) was code like:

// get object from the entity manager
X x = getObjectX(jpaQuery);

if(x == null)
{
    x = new X();
    x.setVariable(foo);
    entityManager.persist(x);
}

With that code in the multi threaded environment I am getting duplicate keys since, I assume, getObjectX returns null for a thread, then that thread is swapped out, the next thread calls getObjextX, also getting null, and then both threads will create and persist a new X().

Short of adding in synchronization, is there an atomic way to get/save-if-doesn't-exist a value with JPA or should I rethink my approach

EDIT:

I am using the latest Eclipselink and MySql 5.1

© Stack Overflow or respective owner

Related posts about java

Related posts about jpa