1

If I have a java code that deals with database and I want to use multi-threading in my application. Each thread suppose to run a function that contains insertion to the database. My question is: Where should I place the following statements:

Connection con = DriverManager.getConnection (dbUrl);
query = " insert into schema.table values (default,?,?)";   
preparedStmt = con.prepareStatement(query);

Should I place them in the run so every thread execute them? or in the Main so they are executed once only? or inside the function that is called by the run function ? I need to know the right method to insert to Database when I have multi-threads. Thanks.

1 Answer 1

2

You should consider creating a ConnectionPool and get connection from this pool for your database related work.

The following two links might be of interest to you:

Connection Pooling
Apache Commons DBCP

Edit Thanks to @MJB for pointing this one out:
c3p0 is another one that is pretty good.
BoneCP is another one

But at the end of the day, the simple point is this: You need to implement connection pooling. Which one you choose is totally your decision and based on your requirements.

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

1 Comment

Connection pooling is probably the best way to deal with this. You might also consider passing messages to the thread that handles database interaction if the other threads do different kinds of jobs.

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.