简体   繁体   中英

Multi-threaded server database access

I'm writing a multi-threaded server in Java that will access a database and return information about the database that is requested by clients.

My main server class is written as a static class that basically spawns a thread when a client connects to it.

My question is where to put all of the database access methods? Should they be located in the static main server class or should they be put in the server thread code?

All answers/explanations are appreciated!

It should be kept in thread part. Because if you use access methods in static server class, then the session object created for database interaction will become thread unsafe. There will be a possibility that your database is left with inconsistencies.

It is advisable that the data base connection part is kept in thread code. It will be good idea to use thread pool. You can tune your performance for database intensive applications.Following are two important docs from oracle regarding this issue.

  1. http://docs.oracle.com/cd/E19159-01/819-3681/abehq/index.html
  2. http://docs.oracle.com/cd/E19159-01/819-3681/abehs/index.html

Opening and closing db connections is not the best idea. Try reusing threads (and their connections) using a thread pool.

Also there are some database systems where you can't have multiple (write) connections. Sqlite is one of them. In cases like that you can make static syncronized methods to access the db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM