Re: Is the Connection class thread save
Posted by: Mark Matthews
Date: March 05, 2005 08:56AM

Jens K�cke wrote:
> Hi,
>
> as stated in the subject im wondering if I can
> share one Connection between different threads.
> I'm currently writing a server and I would like to
> connect to the database only once and then just
> create a new Statement for every client that
> connects to my server (which starts a new
> thread).
>
> Is that possible or do I have to establish a new
> Connection every time a client connects?
>
> Jens

Jens,

Even though Connection is thread-safe, the JDBC API is not multithread _friendly_, there's too much state that is shared between Connections, statements and result sets to make it work well in a multi-thread situation.

You're also not going to see any performance benefit from sharing a connection between threads, as MySQL can only handle one query at a time on a given connection (which is the same for most RDBMSs), so you will be effectively serializing your application once you hit any amount of load (or if your queries take a long time).

It is much better to either 1) Use a connection pool, so that threads only have a reference to a connection when they need it or 2) Give each thread its own connection.

-Mark

Mark Matthews
Consulting Member Technical Staff - MySQL Enterprise Tools
Oracle
http://www.mysql.com/products/enterprise/monitor.html

Options: ReplyQuote


Subject
Written By
Posted
Re: Is the Connection class thread save
March 05, 2005 08:56AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.