Spring同步方法NOT SYNCHRONIZED [英] Spring synchronized method NOT SYNCHRONIZED

查看:120
本文介绍了Spring同步方法NOT SYNCHRONIZED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:


  • apache tomcat 7

  • java 7

  • oracle 11g

  • eclipse

  • apache jmeter 2.1

  • spring

  • hibernate



    我正在开发一个Web应用程序,它接收来自客户端的请求并根据要使用的请求类型为它们生成序列号在进一步处理中。
    为了生成一个唯一的序列号,我有一个方法从DB获取当前序列号并将其增加1,然后用新的序列号更新该记录。


>

函数:

  @Transactional 
public synchronized Long generateSequenseNumber字符串requestType){
//获取此请求的当前序列号
//将其增加一个
//将其更新为DB

}

该函数可以正常工作,但问题是当我从压力测试工具(JMeter)调用应用程序发送50个请求每秒我得到异常:

  org.hibernate.StaleObjectStateException:行被另一个事务更新或删除(或未保存的值映射不正确):[

虽然函数已同步。



任何建议都会有所帮助。感谢。

解决方案

问题在于@Transactional在进入synchronized方法之前开始会话并在方法完成后提交更改,所以对数据库的更改将不会应用于synchronized方法内。

请检查 Spring @Transactional 第10.5.1节。



您可以尝试在调用此方法时添加同步块,而不是使其同步:

  synchronized(this){
generateSequenseNumber();
}


Environment:

  • apache tomcat 7
  • java 7
  • oracle 11g
  • eclipse
  • apache jmeter 2.1
  • spring
  • hibernate

    I am working on a web application that receives requests from clients and generate sequence number for them according to the request type to be used in further processing. For generating a unique sequence number I have a method to get current sequence number from DB and increment it by 1 then update that record by new sequence number.

The function:

    @Transactional
public synchronized Long generateSequenseNumber(String requestType) {
     //get current sequence number for this requestType
            //increment it by one
            //update it in DB

}

The function works fine, but the problem is when I call the application from stress testing tool (JMeter) to send 50 requests per second I get below exception:

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [

although the function is synchronized.

Any suggestion will be helpful. Thanks.

解决方案

The problem is that @Transactional begins the session before entering the synchronized method and commits the changes after the method is finished, so changes to the database will not be applied inside the synchronized method.

Please check Spring @Transactional section 10.5.1.

You can try adding a synchronized block when calling this method instead of making it synchronized:

synchronized(this){
   generateSequenseNumber();
}

这篇关于Spring同步方法NOT SYNCHRONIZED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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