Reputation: 3065
Does the recursion heavily impose on processor and ram? I mean, that one of my threads has a method, that is very likely to call itself. Let's say that It can self-call about one time per second. My app should run for at least 24 hours without stopping, so it gives (60*60*24) 86400 self-called methods.
How does it influence on the second (main) thread?
Sorry for my bad english, and for no code, but im not writing from home.
Upvotes: 6
Views: 6183
Reputation: 54074
Recursive calls are very inefficient in terms of memory.
This is because each recursive call adds a new frame to the stack and so for N
calls you have O(N)
memory requirements.
Recursive methods solve difficult problems in a really simple way (e.g. traversal of a tree) with simple code.
The downside is that if you don't know what you are doing you could get run out of memory as a result of too many recursive calls.
So if you know that a problem can be solved recursivelly but you need too much recursion try to implement it iteratively (most but not all recursive algorithms can be transformed to iterative ones)
Example. In my Windows 32-bit (4GB) the following gets a Exception in thread "main" java.lang.StackOverflowError
after 7380 calls
public static void recursing( int n ){
System.out.println(n++);
recursing(n);
}
public static void main(String[] args) {
recursing(1);
}
Upvotes: 4
Reputation: 533482
In Java, using a loop is often more efficient than using recursion. There are some cases where recursion is the most efficient.
One processor can easily make 10 million calls per second or trillions per day. 86400 isn't that much and I wouldn't worry about.
Let's say that It can self-call about one time per second.
That doesn't make much sense. Using a loop is a much approach. Only use recursion if you intend to return when finished.
Upvotes: 1
Reputation: 1749
I'm not sure if it is appropriate to your problem, but it sounds like a scheduler maybe useful as you are basically saying that it should run once a second. You could try using the Quartz Scheduler.
You can create a Job and then by using a simple trigger or cron trigger tell it to run every second forever. Documentation for Quartz.
Upvotes: 1
Reputation: 503
If there are no return statements which will end the string of recursive calls before the 86400th call, it is likely that you will have a stack overflow error from there being too many recursive calls on the stack. Try implementing an iterative solution if possible.
Upvotes: 8