开发者

How can i get an immediate response from a long running process in j2ee?

I can't seem to find a solid answer anywhere. I THINK i found one with respect to JMS but it was开发者_StackOverflow社区 confusing.


It really depends what stack of j2EE are you using? Is it just web, ejb layer or both?. If we are talking about the web then you can use asynchronous servlet introduced in the newest Java EE specification, if you are using plain EJB's then the natural choice would be Messege driven beans (mentioned JMS). You can of course design a custom solution where for example you send some data to process and then the j2ee application itself calls your application (with http request for example) to notify that its done running the job. Possibilities are endless and if one is better than other always depends on the specific scenario.


If I understand correctly what you are talking about is the ability to start a task (that will take some time) then respond to the user while that task is still doing it's stuff. Depending on your requirements it is really quite simple and you can use a plain old Java Thread to perform the operation.

public class DoSillyCounting extends Thread {
    private volatile int counter;
    public int getCounter() { return counter; }
    public run() {
        while (counter < 10) {
            counter ++;
            try { Thread.sleep(1000); }
            catch (InterruptedException ie) { }
        }
    }
}

In your setup page you might do this: (session is an HttpSession)

DoSillyCounting doSillyCounting = new DoSillyCounting();
doSillyCounting.start();
session.putValue("tenSecondsCounter", doSillyCounting);
/* Here you can respond to the user while the Thread is executing */

And in your status page you might do this:

DoSillyCounting doSillyCounting =
    (DoSillyCounting)session.getValue("tenSecondsCounter");
out.print(Integer.toString(doSillyCounting.getCounter());
if (doSillyCounting.isAlive()) {
    out.print("Still Working on it");
} else {
    out.print("Yippee, I finished");
}

Of course, this is a rather useless example and this model is not a good idea when you may have a large number of requests to satisfy, it would then be worth looking at a ThreadPool implementation or using something like JMS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜