开发者

Infinite function call, Recursion or Timer?

I'm working on a Java function that should be called infinitely. This function will call a web service that will return back results. Results are then parsed and analysed.

The function should not be called again until the web service returns results, and these results are analysed.

Should I be using infinite recursion to a开发者_JS百科chieve this? Or should I be using a timer that calls the function on certain intervals?

Some questions arise as well:

  1. What happens if the web service's response times out? How can I prevent the application from crashing or making unlimited calls with no response?

  2. Should I be creating an event driven class to handle these requests?

  3. In terms of optimization, which of the solutions is more efficient?

-- Edit

I understand the question is a bit vague and general, so non detailed answers will do just fine, I'll focus on the implementation. I just need an advice on the approach. :)

Any help is appreciated.


You almost certainly should not use recursion for a process that doesn't have a definite "base case". Infinite recursion is a horribly bad idea. Each call eats up more and more of your stack, and eventually you'll die with an OOM error (or stack overflow, if Java differentiates between the two).

You could try something like

private Object mutex = new Object();
private boolean yourTaskIsRunning = false;

protected void yourTask()
{
    synchronized(mutex)
    {
        if (yourTaskIsRunning) return;
        yourTaskIsRunning = true;
    }
    try
    {
        // do your thing
    }
    finally
    {
        yourTaskIsRunning = false;
    }
}

Or, if you can bundle your task into a distinct object, use its being null or not as the "task is running" flag. Create the object in the first synchronized section, start it in the "do your thing" section, and set it to null in the finally block. (Note, either way, you'll need to ensure that all non-fatal paths through the function -- even thrown exceptions! -- "clear the flag" when they're done. Hence the finally block.)

Either way, you can set up a timer to call this function, and it'll immediately return if it's already running. The only drawback with the timer approach is that there might be some downtime between when one call ends and the next begins.


I am confused. Why would you need a timer?

Seems like the calls are synchronous i.e. the next one does not fire until you receive the response from the first one.

Why not just a simple while loop with a try/catch block catching the java.net.SocketTimeoutException and breaking out of the loop on certain number of failures?

Recursion as suggested seems like a bad idea for this use case.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜