Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

hibernate - Spring synchronized method NOT SYNCHRONIZED

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...