Spring synchronized method NOT SYNCHRONIZED

前端 未结 2 708
甜味超标
甜味超标 2020-12-17 04:58

Environment:

  • apache tomcat 7

  • java 7

  • oracle 11g

  • eclipse

  • apache jmeter 2.1

相关标签:
2条回答
  • 2020-12-17 05:24

    Extending Azizi's answer...

    @Transactional makes Spring wrap the class in AOP proxy. The target method execution is then wrapped in transaction interceptor. So the overall call looks like this:

    -> FooProxy#generateSequenseNumber
       -> TransactionInterceptor#invoke
          -> BEGIN TRANSACTION
             -> Foo#generateSequenceNumber (synchronized)
          -> COMMIT|ROLLBACK TRANSACTION
    

    You can (and should) try to put breakpoint inside your method to see what is on the stack.

    If you want to solve the synchronization inside your generateSequenseNumber method, then you can use TransactionTemplate and REQUIRES_NEW propagation. Of course then the @Transactional annotation would make no sense.

    0 讨论(0)
  • 2020-12-17 05:34

    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();
    }
    
    0 讨论(0)
提交回复
热议问题