JPA原子查询/保存多线程应用程序 [英] JPA atomic query/save for multithreaded app

查看:260
本文介绍了JPA原子查询/保存多线程应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在改变我的JP​​A代码以利用线程。我为每个线程都有一个单独的实体管理器和事务。

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);
}

在多线程环境中使用该代码我得到重复的密钥,因为,我假设,getObjectX为一个线程返回null,然后该线程被换出,下一个线程调用getObjextX,也变为null,然后两个线程将创建并持久化一个新的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().

没有同步添加,是否有一种原子方法来获取/保存 - 如果不存在JPA值或者我应该重新考虑我的方法

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

编辑:

我使用的是最新的Eclipselink和MySql 5.1

I am using the latest Eclipselink and MySql 5.1

编辑2:

我添加了同步... MASSIVE性能命中(达到无法使用的程度)。要收集主线程上的所有数据,然后在该线程上进行创建。

I added synchronization... MASSIVE performance hit (to the point that it cannot be used). Going to gather all of the data up back on the main thread and then do the creations on that thread.

推荐答案

简短的答案是不是JPA API不能为您做到这一点。整个API或多或少地围绕假设事情将会起作用并在并发修改时抛出异常的乐观原则构建。

Short sad answer is no the JPA API cannot do that for you. The whole API is more or less built around the optimistic principle of assuming things are going to work and throwing exceptions in the event of concurrent modification.

如果这种情况经常发生,可能有一些其他组件(无论生成foo?)可以从线程安全中获益,也许是在查询+创建时同步的替代方法。

If this is happening often, there's likely some other component (whatever generates foo?) that could benefit from being made threadsafe, as perhaps an alternative to synchronizing around the query+create.

这篇关于JPA原子查询/保存多线程应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆