JPA: pattern for handling OptimisticLockException JPA: pattern for handling OptimisticLockException database database

JPA: pattern for handling OptimisticLockException


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.


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.


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.