Search code examples
javadatabasesynchronizationdatabase-lockingrowlocking

How to obtain a row level lock in java when multiple JVMs accessing same data base?


I have three instances of same application running in different JVMs. I don't want a specific value in the data base to modified by different applications at the same time. How do I enforce this restriction in java?


Solution

  • It depends on the technology stack you are using.

    1. You may want to consider to do Optimistic or Pessimistic Concurrency Control
    2. If you need pessimistic concurrency control, and if you are using JDBC directly, it will be DBMS-specific for the way to do row lock (some DBMS may not even allow you to do so). For example, in Oracle, you do it by select * from table_name for update
    3. If you are using JPA or Hibernate, it is wrapped by EntityManager.lock(entity)/Session.lock(entity) (something similar)
    4. In some case you don't even need to do anything special.

    Unless you provide more details of your problem, it's very difficult to give you a concrete suggestion.