3

We have a bad performing business method in a StatelessSessionBean. To improve the performance we would like to split this business method up into several asynchronous methods calls.

The problem is that these asynchronous methods have to run in the same transaction (they have to use the same JPA entity manager). As far as I understood the Java EE specification this is not possible using container managed transactions. Is it possible to realize this requirement using bean managed transactions or some other mechanism?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
woelfle
  • 557
  • 1
  • 7
  • 23

1 Answers1

4

You can't do this, neither with standard EJB nor with any extension. A transaction is tied to a database connection which means you would have to share that connection between several threads. This is not safe.

Also asynchronous code may for some reason be executed with large delay, e.g. under high CPU load. This would keep your transaction open for unnecessarily long time.

What are your options? First of all parallelizing SQL queries (especially writes - you need to have them in one transaction) won't give you much. Database are typically I/O bound. Parallelizing is only worth your time when you have CPU-intensive tasks or you are waiting for something.

In both cases redesign your code to perform parallel code in several threads and have only one writer thread, handling the database and transactions. For example if you need to call 10 servers, collect the responses and store them - spawn 10 threads/use a pool, wait for results and store all of them in one thread.

See also

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • The database is not modified by the business method. It is a read only operation. The problem is that we have to ensure that it operates on a snapshot of the database. I.e. we have to make sure that changes to the database made by someone else while the business method is running are not considered. Therefore we used a 'repeadable read' transaction. – woelfle May 11 '12 at 12:26
  • It is a MySQL InnoDB database – woelfle May 14 '12 at 15:33
  • >parallelizing SQL queries won't give you much - Actually, it sometimes does. When you have a DB with a lot of parallel IO capacity it does speed up things. We build systems like this one: http://jdevelopment.nl/one-dvd-per-second (old example, newer ones have 3 or 4 RAID controllers with 24 to 48 SSDs). There, breaking up large queries in 8 or more parallel ones dramatically increases performance and overall utilization of the capacity. – Arjan Tijms Nov 29 '12 at 09:41