JPA: pattern for handling OptimisticLockException

后端 未结 4 1503
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 08:33

what is the correct pattern for handling OLE in a (REST) web service? this is what i\'m doing now, for example,

protected void doDelete(HttpServletRequest re         


        
相关标签:
4条回答
  • 2020-12-14 08:46

    The "politically correct" answer in rest, is to return an HTTP 409 (Conflict) witch matches perfectly with the idea of optimistic locking. Your client should manage it, probably by retring a few seconds later.

    I wouldn't add the logic to retry in your app, as your client will already handle situations when you return a 40X code.

    0 讨论(0)
  • 2020-12-14 08:54

    If you get an optimistic locking exception, it means that some other transaction has committed changes to entities you were trying to update/delete. Since the other transaction has committed, retrying immediately might have a good chance to succeed.

    I would also make the method fail after N attempts, rather than waiting for a StackOverflowException to happen.

    0 讨论(0)
  • 2020-12-14 09:00

    By the way, catch (InterruptedException e) {} is always a bad idea, because the system has asked your computation to cancel, and you are ignoring it. In the context of a web service, an InterruptedException would be another good reason to signal an error to the client.

    0 讨论(0)
  • 2020-12-14 09:03

    If you're just going to keep retrying until it works anyway, why not just disable optimistic locking? You should let the caller know that they made a decision based on out dated information! If you're in control of both sides an appropriate 400 code can be returned. If it's public it can be more friendly to arbitrary clients to just return 500. (Of course then you perpetuate the under-use of appropriate response codes! such a dilemma)

    0 讨论(0)
提交回复
热议问题