How can I use a transaction manager (e.g. Bitronix , JBoss TS or Atomikos ) in Java SE (not Java EE or Spring) to support the following use case:
Suppose we have the following class:
public class Dao { public void updateDatabase(DB db) { connet to db run a sql } }
and we create a Java Runnable from this, as shown below:
public class MyRunnable extends Runnable { Dao dao; DB db; public MyRunnable(Dao dao, DB db) { this.dao=dao; this.db = db; } public run() throws Exception { return dao.updateDatabase(db); } }
Now, in our Service layer, we have another class:
public class Service { public void updateDatabases() { BEGIN TRANSACTION; ExecutorService es = Executors.newFixedThreadPool(10); ExecutorCompletionService ecs = new ExecutorCompletionService(es); List<Future<T>> futures = new ArrayList<Future<T>>(n); Dao dao = new Dao(); futures.add(ecs.submit(new MyRunnable(dao, new DB("db1"))); futures.add(ecs.submit(new MyRunnable(dao, new DB("db2"))); futures.add(ecs.submit(new MyRunnable(dao, new DB("db3"))); for (int i = 0; i < n; ++i) { completionService.take().get(); } END TRANSACTION; } }
And the client can be a servlet or any other multi-threaded environment:
public MyServlet extend HttpServlet { protected void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException { Service service = new Service(); service.updateDatabases(); } }
What will be the correct code for the BEGIN TRANSACTION and END TRANSACTION parts? Is it possible? If not, what needs to be changed? Requirements - to support the updateDatabases () method at the same time (since it will access several databases at the same time) and transactional.
source share