Skip to content
Advertisement

Java async MySQL queries

First of all, I don’t have much experience with thread safe programming.

I have a MySQL class, and I want to use one instance in multiple threads to prevent blocking code in the main thread. I read about connection pooling but I want to keep it as simple as it is.

This is my MySQL class:

JavaScript

Is it possible to make my MySQL class Thread safe with the synchronized keyword, as I already used it in the code above?

I use this class like that from different threads:

JavaScript

My question: Is it thread safe?

Edit:

JavaScript

Advertisement

Answer

Your question: Is it thread safe?

My answer: No, it’s not.

Most simple way to break it: Have one of your threads call mySQL.getConnection().close();

Apart from that: Most connections don’t like parallel statements at all. What should be the transaction scope of that?

You should seriously consider the use of a connection pool instead. My favorite choisce would be c3p0. See http://www.mchange.com/projects/c3p0/#quickstart for a quickstart example.

Making it safe

Instead of passing around an instance of MySQL, you create and configure a ComboPooledDataSource (or any other DataSource you want to use). Then inside your classes, obtain a Connection from that pool, perform your SQL statements and then close it. The most convenient way to do that would be with try-with-resource introduced with Java 7:

JavaScript

Some more info on your existing class

You fail to clean up a whole lot of Statements if you do

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement