Photo by Tim Gouw on Unsplash

Introduction

When it comes to enterprise applications, it is essential to properly manage concurrent access to a database. This means that we should be able to manage multiple transactions efficiently and, above all, without risk of error.

How to use optimistic locking?

To use optimistic locking, we need to have an entity including property with @Version annotation. When in use, each transaction that reads data contains the value of the version property.

Optimistic locking Vs Pessimistic locking?

It is good to know that, unlike optimistic locking, JPA gives us pessimistic locking. This is another mechanism for managing concurrent access to data.

Optimistic locking in details

Like we said before, to use optimistic locking we need to add version attribute in the entity. So we’re going to have something like this.

  • the type of the version attribute must be one of the following: int, Integer, long, Long, short, Short, java.sql.Timestamp

Lock modes

  • Optimistic: is to check the locked entity version towards the end of the current running transaction, to make sure we don’t use a stale entity state.
  • Optimistic increment: it’s like the first mode but in addition, it increments the value of the version attribute.

Explicit use of optimistic locking

Even that, an optimistic lock is available by default, there are several ways to request it explicitly.

Conclusion

In this article, we have become familiar with a tool that can help us orchestrate simultaneous transactions. Optimistic locking uses version attributes included in entities to control simultaneous changes to them.

Software Engineer. I’m not perfect. still running after my dreams. going to the moon 🌑

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store