简体   繁体   中英

Java Concurrent Update for multiple tables With Transaction support

I am looking for a development of a transaction framework, which needs to update the database tables concurrently.

In simple words, a single transaction should update concurrently around 8 independent tables, and the whole transaction should fail if any update thrown error.

Is there any way I can handle it concurrently,

Ie, 10 Threads update 10 Tables and if any update fails all the update should rollback.

Is there any framework which allows to me handle this scenario.

If you use JTA or Spring transaction which will be shared by same connection and defeat the purpose of concurrent update.

Or any way I can write using custom thread based solution.

Why would using JTA or Spring Transaction mean you'll use the same connection? If you configure a connection pool and connect to it correctly, surely you'll get a different connection for each thread that you use?

This just seems like an unusually configured distributed transaction to me, and my first attempt at this would be to use Spring and/or Hibernate. I think you'd just have to ensure that you were treating the transactions as distributed transactions.

The framework is JTA.

It depends from your database whether you can use one connection for all threads. Details can be found here . So in the general case you need a connection for each thread.

If you use an XA data source, you could try to run the concurrent threads under control of a JTA transaction.

This is a lot of complexity, and it takes time to prepare the threads, so it's probably only useful, if the updates take a long time, the affected tables are independent, and you have enough CPUs in your database server.

Update

Regarding transaction propagation, here you can find some thoughts on it.

You can use the standard JDBC. JDBC allows you to share a single Connection among multiple threads. To make several threads work in one transaction you should

  • create a java.sql.Connection / or take it from pool
  • turn autocommit off
  • run concurrent tasks with the same connection
  • wait for the tasks to finish
  • commit if all tasks finished successfully; rollback otherwise
  • close connection

It is also possible to use Spring JDBC if you use Spring's SingleConnectionDataSource

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM