• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

StackOverflowError when defining Instance of Class

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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]
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got the concept. Thanks for the prompt reply.
reply
    Bookmark Topic Watch Topic
  • New Topic