Tutorial about Using multi-threading in jdbc Tutorial about Using multi-threading in jdbc multithreading multithreading

Tutorial about Using multi-threading in jdbc


Multi-threading will improve your performance but there are a couple of things you need to know:

  1. Each thread needs its own JDBC connection. Connections can't be shared between threads because each connection is also a transaction.
  2. Upload the data in chunks and commit once in a while to avoid accumulating huge rollback/undo tables.
  3. Cut tasks into several work units where each unit does one job.

To elaborate the last point: Currently, you have a task that reads a file, parses it, opens a JDBC connection, does some calculations, sends the data to the database, etc.

What you should do:

  1. One (!) thread to read the file and create "jobs" out of it. Each job should contains a small, but not too small "unit of work". Push those into a queue
  2. The next thread(s) wait(s) for jobs in the queue and do the calculations. This can happen while the threads in step #1 wait for the slow hard disk to return the new lines of data. The result of this conversion step goes into the next queue
  3. One or more threads to upload the data via JDBC.

The first and the last threads are pretty slow because they are I/O bound (hard disks are slow and network connections are even worse). Plus inserting data in a database is a very complex task (allocating space, updating indexes, checking foreign keys)

Using different worker threads gives you lots of advantages:

  1. It's easy to test each thread separately. Since they don't share data, you need no synchronization. The queues will do that for you
  2. You can quickly change the number of threads for each step to tweak performance


Multi threading may be of help, if the lines are uncorrelated, you may start off two processes one reading even lines, another uneven lines, and get your db connection from a connection pool (dbcp) and analyze performance. But first I would investigate whether jdbc is the best approach normally databases have optimized solutions for imports like this. These solutions may also temporarily switch of constraint checking of your table, and turn that back on later, which is also great for performance. As always depending on your requirements.

Also you may want to checkout springbatch which is designed for batch processing.


As far as I know,the JDBC Bridge uses synchronized methods to serialize all calls to ODBC so using mutliple threads won't give you any performance boost unless it boosts your application itself.