如何在Java SE(而非Java EE或Spring)中使用事务管理器(例如Bitronix,JBoss TS或Atomikos)来支持以下用例:
假设我们有以下类:
public class Dao {
public void updateDatabase(DB db) {
connet to db
run a sql
}
}
然后我们从中创建一个Java Runnable,如下所示:
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);
}
}
现在在我们的服务层中,我们有另一个类:
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;
}
}
客户端可以是Servlet或任何其他多线程环境:
public MyServlet extend HttpServlet {
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
Service service = new Service();
service.updateDatabases();
}
}
BEGIN TRANSACTION 和 END TRANSACTION 的正确代码是什么?这可行吗?如果不行,需要做哪些改变?要求保持 updateDatabases() 方法并发(因为它将同时访问多个数据库)和事务性。