添加到子集合的多个线程导致StaleObjectStateException

时间:2013-03-28 20:28:49

标签: multithreading spring hibernate

我有一种情况,多个线程加载相同的实体Job,然后每个线程添加到其子集合Set<JobError>。如果父级本身已更新,我可以理解这个异常,但对父级的唯一“改变”是对集合的添加,即便如此吗?

家长实体:

@Entity
@Table(name = "JOB")
public class Job extends BaseEntity {

private Set<JobError> jobErrors = new HashSet<JobError>();


/**
 * @return the jobErrors
 */
@OneToMany(mappedBy = "job", cascade = { CascadeType.PERSIST,
        CascadeType.MERGE, CascadeType.REMOVE })
public Set<JobError> getJobErrors() {
    return jobErrors;
}

/**
 * @param jobErrors
 *            the jobErrors to set
 */
public void setJobErrors(Set<JobError> jobErrors) {
    this.jobErrors = jobErrors;
}

/**
 * Helper to take care of both sides of the association
 * @param message
 * @param currentProfileId
 */
public void addError(String message, Long currentProfileId,
        String firstName, String lastName) {
    JobError er = new JobError(message, currentProfileId, firstName,
            lastName, this);
    jobErrors.add(er);
}
}

儿童实体:

@Entity
@Table(name = "JOB_ERROR")
public class JobError extends BaseEntity {
private Job job;

    public JobError(String description, Long profileId, String firstName,
        String lastName, Job job) {
    this.description = description;
    this.profileId = profileId;
    this.firstName = firstName;
    this.lastName = lastName;
    this.job = job;
}
/**
 * 
 */
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "JOB_ID", nullable = false)
public Job getJob() {
    return job;
}

/**
 * @param jobErrors
 *            the jobErrors to set
 */
public void setJob(Job job) {
    this.job = job;
}
}

服务代码,它在多个并发线程中运行:

job = jobDao.findById(er.getJobId(), false);

for (Long profileId : er.getProfileIds()) {
// do stuff
try {
    sendEmail(emailTemplateDto, user);
} catch (RuntimeException re) {
    job.addError(re.getLocalizedMessage(), currentProfileId, profile.getPersonalData().getFirstName(), profile.getPersonalData().getLastName());
}

一旦返回的服务方法注释为@Transactional(propagation = Propagation.REQUIRED),就抛出StaleObjectStateException:

2013-03-28 13:22:52,578 ERROR     org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(324):  - Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.test.project.domain.Job#2]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1950)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2594)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2494)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2821)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:467)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy162.processSendEmail(Unknown Source)
at com.test.project.service.messaging.EmailRequestMessageListener.onMessage(EmailRequestMessageListener.java:57)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:560)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:498)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:467)
at org.springframework.jms.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:439)
at org.springframework.jms.listener.SimpleMessageListenerContainer.processMessage(SimpleMessageListenerContainer.java:311)
at org.springframework.jms.listener.SimpleMessageListenerContainer$2.onMessage(SimpleMessageListenerContainer.java:287)
at org.apache.activemq.ActiveMQMessageConsumer.dispatch(ActiveMQMessageConsumer.java:1321)
at org.apache.activemq.ActiveMQSessionExecutor.dispatch(ActiveMQSessionExecutor.java:131)
at org.apache.activemq.ActiveMQSessionExecutor.iterate(ActiveMQSessionExecutor.java:202)
at org.apache.activemq.thread.PooledTaskRunner.runTask(PooledTaskRunner.java:129)
at org.apache.activemq.thread.PooledTaskRunner$1.run(PooledTaskRunner.java:47)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

除了试图直接保存JobError之外我别无其他。目前我首先加载Job,添加到JobError的集合,然后添加merge Job,并希望cascade.merge将负责保存子集合。

任何指针都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

我不知道这是否是导致异常的原因,但如果不是这会导致问题:HashSet不是线程安全的集合,这意味着如果两个线程调用addError at同时,其中一个错误可能无法进入集合。您需要将“synchronized”关键字添加到addError方法中,否则您需要使用线程安全的替代方法替换HashSet,例如ConcurrentLinkedQueue或ConcurrentHashMap