Kasun
Kasun

Reputation: 561

How to deal with Java EE concurrency

Please let me know the best practices of providing application concurrency in software project. I would like to use Hibernate for ORM. Spring to manage the transactions. Database as MySQL.

My concurrency requirement is to let as much as users to connect to the database and
make CRUD operations and use the services. But I do not like to have stale data.

  1. How to handle data concurrency issues in DB.
  2. How to handle application concurrency. What if two threads access my object simultaneously will it corrupt the state of my object?
  3. What are the best practices.
  4. Do you recommend to define isolation levels in spring methods @Transactional(isolation=Isolation.READ_COMMITTED). How to take that decision.?

I have come up with below items would like to know your feedback and the way to address?

a. How to handle data concurrency issues in DB. Use Version Tag and Timestamp.

b. How to handle application concurrency. Provide optimistic locking. Not using synchronizations but create objects for each requests (Scope prototype).

c. What are the best practices. cache objects whenever its possible.

Upvotes: 0

Views: 310

Answers (1)

JB Nizet
JB Nizet

Reputation: 691665

  1. By using transactions, and @Version fields in your entities if needed.
  2. Spring beans are singletons by default, and are thus shared by threads. But they're usually stateless, thus inherently thread-safe. Hibernate entities shouldn't be shared between threads, and aren't unless you explicitely do it by yourself: each transaction, running in its own thread, will have its own Hibernate session, loading its own entity instances.
  3. much too broad to be answered.
  4. The default isolation level of your database is usually what you want. It is READ_COMMITTED with most databases I know about.

Regarding your point c (cache objects whenever possible), I would say that this is exactly what you shouldn't do. Caching makes your app stateful, difficult to cluster, much more complex, and you'll have to deal with the staleness of the cache. Don't cache anything until

  • you have a performance problem
  • you can't tweak your algorithms and queries to solve the performance problem
  • you have proven that caching will solve the performance problem
  • you have proven that caching won't cause problems worse than the performance problem

Databases are fast, and already cache data in memory for you.

Upvotes: 3

Related Questions