• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StackOverflowError when defining Instance of Class

 
Kewat Ajay
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting StackOverflowError while executing below program:



Error Description:

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)
at com.threadEx.ThreadEx2.<init>(ThreadEx2.java:3)
at com.threadEx.ThreadEx2.<init>(ThreadEx2.java:9)
at com.threadEx.ThreadEx2.<init>(ThreadEx2.java:9)

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]
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kewat. Welcome to The Ranch!

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.
 
Kewat Ajay
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got the concept. Thanks for the prompt reply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic