且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

需要帮助java web应用程序设计执行后台任务

更新时间:2023-02-09 16:47:38

将创建由容器管理的应用程序范围的线程池。如何做取决于使用的容器。如果你的容器不支持它(例如Tomcat)或者你想要与容器无关,那么基本的方法是实现 ServletContextListener ,使用Java 1.5提供的帮助创建线程池 ExecutorService API在启动时关闭并关闭线程池。如果你不是Java 1.5,或者想要更多的抽象,那么你也可以使用 Spring的 TaskExecutor



有关于并发实用程序,但它还没有进入Java EE 6。 p>

相关问题:




I have a local web app that is installed on a desktop PC, and it needs to regularly sync with a remote server through web services.

I have a "transactions" table that stores transactions that have been processed locally and need to be sent to the remote server, and this table also contains transactions that have retrieved from the remote server (that have been processed remotely) and need to be peformed locally (they have been retrieved using a web service call)... The transactions are performed in time order to ensure they are processed in the right order.

An example of the type of transactions are "loans" and "returns" of items from a store, for example a video rental store. For example something may have been loaned locally and returned remotely or vice versa, or any sequence of loan/return events.

There is also other information that is retrieved from the remote server to update the local records.

When the user performs the tasks locally, I update the local db in real time and add the transaction to the table for background processing with the remote server.

What is the best approach for processing the background tasks. I have tried using a Thread that is created in a HTTPSessionListener, and using interrupt() when the session is removed, but I don't think that this is the safest approach. I have also tried using a session attribute as a locking mechanisim, but this also isn't the best approach.

I was also wondering how you know when a thread has completed it's run, as to avoid lunching another thread at the same time. Or whether a thread has ditched before completing.

I have come accross another suggestion, using the Quartz scheduler, I haven't read up on this approach in detail yet. I am going to puchase a copy of Java Concurrency in Practice, but I wanted some help with ideas for the best approach before I get stuck into it.

BTW I'm not using a web app framework.

Thanks.

Safest would be to create an applicationwide threadpool which is managed by the container. How to do that depends on the container used. If your container doesn't support it (e.g. Tomcat) or you want to be container-independent, then the basic approach would be to implement ServletContextListener, create the threadpool with help of Java 1.5 provided ExecutorService API on startup and kill the threadpool on shutdown. If you aren't on Java 1.5 yet or want more abstraction, then you can also use Spring's TaskExecutor

There was ever a Java EE proposal about concurrency utilities, but it has not yet made it into Java EE 6.

Related questions: