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 achieve this? Or should I be using a timer that calls the function on certain intervals?
Some questions arise as well:
-
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?
-
Should I be creating an event driven class to handle these requests?
-
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
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
synchronizedsection, start it in the “do your thing” section, and set it to null in thefinallyblock. (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 thefinallyblock.)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.