2

I have an application which runs some multi-threading process.
In each thread I'm sharing the same connection to my mysql db which store information important for the thread to run.

Usually when multi-threading I must check for synchronization so I want to share the same resource at the same time, but do I have to do the same with mysql?

I'm using innodb which locks the row when using it, and I don't know if I need to look the access to it in my code too.

To my understanding it doesn't matter if I do it or not because the server it self manage its connection but again I'm not sure.

1

1 Answer 1

1

Connections in java are not guaranteed to be thread safe.

In addition to that, Mysql (and innodb in particular) can handle multiple connections safely.

In a comment to you question (by Emil Vikström), solutions are proposed to your problem;

(Edit) and I quote:

Have you checked out one of the multiple questions dealing with this topic already? For example: Java Threads and MySQL and Is MySQL Connector/JDBC thread safe? – Emil Vikström

Sign up to request clarification or add additional context in comments.

4 Comments

i've actually did read those questions, but as you said, in logical matter i don't understand what are the problems that can happen when using a connection to a shared innodb. and if i am using a shared simple connection between thread, should i synchronized them ? or the mysql knows how to work with them alone..
I have not tried it myself but 2 threads or more using 1 connection object may give undefined results. This is due to the fact that the underlying implementation may maintain the actual connection state (socket, resultSets and etc.). The best practice is to use a connection pool, 1 connection per thread or synchronize same connection usage. So to your question, yes - you should synchronize shared connection.
Doesnt opening a new connection per thread might overload the mysql server?
You should try and experiment all the ways to see what happens. I recommend not doing premature optimization and keeping it simple. You can always look for bottlenecks after you have a concrete implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.