Java Safe Recursion

Problem: Getting StackOverflowError in java recursion

Exception in thread "main" java.lang.StackOverflowError
at java.nio.Buffer.<init>(Buffer.java:176)
at java.nio.CharBuffer.<init>(CharBuffer.java:259)
at java.nio.HeapCharBuffer.<init>(HeapCharBuffer.java:52)
at java.nio.CharBuffer.wrap(CharBuffer.java:350)
at sun.nio.cs.StreamEncoder$CharsetSE.implWrite(StreamEncoder.java:378)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:136)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:191)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
at java.io.PrintStream.write(PrintStream.java:458)
at java.io.PrintStream.print(PrintStream.java:602)
at java.io.PrintStream.println(PrintStream.java:739)
at com.test.RecursiveLock.checkLogicOne(RecursiveLock.java:25)
at com.test.RecursiveLock.checkLogicOne(RecursiveLock.java:27)
at com.test.RecursiveLock.checkLogicOne(RecursiveLock.java:27)
at com.test.RecursiveLock.checkLogicOne(RecursiveLock.java:27)
at com.test.RecursiveLock.checkLogicOne(RecursiveLock.java:27)

Please check this code for better understanding 

package com.test;

public class RecursiveLock {

	public static void main(String[] args) {

		try {
			RecursiveLock rl = new RecursiveLock();
			 //rl.checkLogicOne(1);
			rl.checkLogicOneSafe(1);

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * This is not infinite. This fails with Stack Overflow error
	 *
	 * @param i
	 */
	private void checkLogicOne(long i) {
		try {
			System.out.println("Running " + i);
			// Thread.sleep(100);
			checkLogicOne(i + 1);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private static int recursionCounter = 0;
	private static int REC_LIMIT = 1000;

	/**
	 * Dont assume that data is available and system will come out smoothly.
	 * without safe check, it may enter into stack overflow.
	 *
	 * @param i
	 *
	 */
	private void checkLogicOneSafe(long i) {
		try {
			System.out.println("Running " + i);

			// This prevents Stack Over Flow
			if (recursionCounter > REC_LIMIT) {
				System.out.println("Exceeded Recursion Limit");
				return;
			} else
				recursionCounter++;

			checkLogicOneSafe(i + 1);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s