Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java multithreading

 
Richard Ellison
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
How do I design Java applications which talk to a database from the point of view of multithreading.Meaning in case of a situation where data may be updated/retrieved by multiple threads,do I leave it to the database(pagelocks,rowlocks etc) to take care of this situation or should I be taking care to synchronize blocks or methods on the Java side?

Thanks
Richard
 
Lester Burnham
Rancher
Posts: 1337
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All DB updates should be part of a transaction (which is managed through the Connection object) - that's sufficient for the DB to make sure that simultaneous updates do not clobber one another.

It gets tricky if data is updated by one thread while at the same time it's read by another thread. In that case you can't be sure whether the old or the new data will be returned. If that's important you should look into the concept of "transaction isolation levels" (which is also handled through the Connection object).
But most applications ignore this aspect and just display whatever data the DB returns. Worst case would be that you get data which is obsolete as of a few milliseconds ago.
 
Richard Ellison
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for some tips.

Regards
Richard.
 
Sergey Babkin
author
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can either have one connection to the database per program or one connection per thread. If one connection per program, then it must be either used in a dedicated thread or access to it synchronized. With one connection per thread, they can do pretty much whatever they please (but having too many connections is probably bad too).
 
We noticed he had no friends. So we gave him this tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!