Search code examples
javarecursionstack-overflow

How to solve this StackOverflowError in this bad recursion example?


I'm having a programming issue related to bad recursion and StackOverflowError. I've got this case in a separate thread:

public void subscribe(final String channel) {
   try {
      // blocking command
      client.subscribe(channel);
   } catch(ConnectionException e) {
      subscribe(channel);
   }
}

Say this ConnectionException is only happening periodically (something like every minute). After a few hundreds, I obviously obtain a StackOverflowError.

I know what's happening but I have no idea how I could solve this (i.e re-subscribing silently without increasing the calling stack). Any ideas?


Solution

  • Why not using a simple loop like his?

    public void subscribe(final String channel) {
       while(true){
           try {
              // blocking command
              client.subscribe(channel);
              return;
           } catch(ConnectionException e) {
              // ignored
           }
       }
    }