0

I am working on a warehouse management system, using JPA 2.0 - EclipseLink and I have come across the need to implement concurrent transactions, currently I am implementing a timestamp difference to validate the last time the quantities are altered: added, removed, transferred.

This strategy seems a bit flawed, and requires a lot of manual verification's, that may create bugs, are there alternative methods of doing this that are provided by the JPA framework?

1
  • Does optimistic locking not work for you? Commented Sep 8, 2012 at 12:03

1 Answer 1

1

As far as I understand you are trying to implement an optimistic locking strategy with timestamps.

JPA provides out of the box an optimistic locking mechanism with the help of a version field. Basically you have a version field (short, int, long or Timestamp) in your entities that is incremented/set on every modification of the entity.

If an entity has a different version at save time than the version it had at load time an OptimisticLockingException is thrown meaning that another user/thread modified the entity in between. You can catch this exception and decide what do:

  • tell the user that saved second to restart its modification
  • merge the modifications (if possible)
  • overwrite

It depends on the usecase.

See also: oracle javaee 6 tutorial on optimistic locking

Sign up to request clarification or add additional context in comments.

2 Comments

That is exaclty what I was looking for, I have two views of Origin and Destiny Products, and these can get updated by concurrent users, if that happens a warning is lauched and the user has to restart the transfer operation. I will replace my implementation with the one provided by JPA. Many Thanks!
Well you might not always be able to catch OptimisticLockingException. There's a possibility the bean is managed by a container, or has a remote interface. You might just get a container-initiated ÈJBException, perhaps not even wrapped around the origin. All that is required by the container is to _log_ OptimisticLockingException. If you need this fine grained control, make sure you call the method EntityManager#flush` in a try/catch block at the end of your business logic. If locking fails, you'll catch the OptimisticLockingException for sure and can do whatever you like with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.