Java thread safe database connections

你。 提交于 2019-12-01 08:30:21

I don't think that making database connections thread-safe is a common practice. Usually what you want is either:

  • Serialize the access to some part of your servlet, so that there is no more than one servlet executing code at a time (ex implementing the SingleThreadModel interface).
  • Locking a particular table/table page/row so you can operate on some particular tuple (by changing the database isolation level).
  • Using optimistic locking to detect modified rows in a table (using some reference attribute of the table to check if the current version is the same that the one in the table).

AFAIK, the typical use of ThreadLocal is to store a unique database connection per thread, so that the same connection can be used in different methods in your business logic without the need of passing it as a parameter each time. Because the common servlet container implementation uses a thread to fullfil an HTTP request, then two different requests are garanteed to use two different database connections.

I know you said you don't want to use libraries to do this, but you're going to be way better off if you do. Pick a standard connection pool (C3P0, DBCP, or something) and you'll be way happier than if you bake your own. Why can't you use a library to do this?

I am not sure why you want your DB connections to be thread safe. Most of the time establishing connection to the database is the longest part of the transaction. Typically connections are reused between requests and pools of open connections are managed (via frameworks or more typically application servers).

If you are worried about concurrent modifications to the same tables you might want to look at synchronized methods: http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!