I am getting StackOverflowError while executing below program:
Exception in thread "main" java.lang.StackOverflowError
at java.security.AccessControlContext.optimize(Unknown Source)
at java.security.AccessController.getContext(Unknown Source)
at java.lang.Thread.init(Unknown Source)
at java.lang.Thread.<init>(Unknown Source)
Now if At Line 1 where I have instantiated an object of Class, if the same program is run with below statement,
public static ThreadEx2 ex = new ThreadEx2();
No such error is observed. Can somebody help me on solving on this.
[Edit - added code tags - see UseCodeTags for details]
In your original version, you have an initialisation statement within ThreadEx2 creating a new ThreadEx2. So every time you create a ThreadEx2 it creates another ThreadEx2 which creates another ThreadEx2 which creates another ThreadEx2......this continues until it runs out of space to store the "stack" of calls in, and you get a StackOverflowError.
In your second version it's static, so there's only one instance for the class. So you create a ThreadEx2 when the class is loaded, and then stop. The only others ones created are the ones you create explicitly after that.