user1167253
user1167253

Reputation: 833

Hibernate, high concurrency issue

I have the following problem. There is a transaction, the following makes.

transaction:

  1. Look in the database, if an object with parameters available.
  2. If not, then create this object, otherwise, change the object and do update.

Suppose we have two transactions (T1 and T2) that are executed in parallel.

T1 looks at the database, there is no object. A millisecond later, T2 looks at the database, there is also no object.

T1 saves the object into the database and it also makes T2.

We have two objects in the database instead of one.

We can I solve this problem?

I'm using: Hibernate + Spring + Tomcat

Thank you.

Upvotes: 1

Views: 484

Answers (2)

Andrzej Bobak
Andrzej Bobak

Reputation: 2112

For application deployed on one server the solution is very simple. Give the function "synchronized" attribute. This way you will be sure this problem won't happen.

The problem may occur though if you run this application on multiple servers. In this case you should think of one centralised database access mechanism.

This can be done also using sql server's features. Create a stored procedure on the database server and give it a proper isolation level. You can read about it here: set isolation level for postgresql stored procedures

Upvotes: 2

Peter Perháč
Peter Perháč

Reputation: 20782

there would be a primary key violation if two of the same objects were inserted into the database and so one of your transactions would fail to write and will roll back. just make sure the objects must be unique by placing relevant constraints on their attributes.

Upvotes: 0

Related Questions