Search code examples
multithreadingjpa-2.0java.util.concurrentoptimistic-lockingoptimistic-concurrency

Handle Concurrency Java level vs database/JPA level


Scenario: In any kind of online Reservation application there is possiblty that people may acesses the application at the same time. Because of this there could be a concurrency issues in that perticular application.

Problem:

In this case, if one or more people accessing the application at a time then there is a problem of concurrency issue.

To solve concurrency the issue we have two solutions

1) Java Concurrency at Client level

2) JPA Optimistc or Pessimistic Locking at persistence level

If the database contains 10 millions or more records then which one is the optimal solution?


Solution

  • Performance issues and Concurrency issues are two different problem domains altogether. Its better not to mix both.

    Regarding concurrency issues: Java Concurrency or Multi threading may be of very limited use in a online reservation system. To avoid problem of lost updates, you must use either JPA Optimistic Locking (preferably) or Pessimistic Locking. That's because if multiple instances of your application are running in parallel (or multiple threads) then its impossible to avoid lost updates using JVM level thread-safety techniques.

    You can refer to the below tutorials:

    1. JPA Optimistic Locking - Oracle Blog
    2. The Java EE 6 Tutorial