aspose file tools*
The moose likes Threads and Synchronization and the fly likes StackOverflowError when defining Instance of Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "StackOverflowError when defining Instance of Class" Watch "StackOverflowError when defining Instance of Class" New topic
Author

StackOverflowError when defining Instance of Class

Kewat Ajay
Greenhorn

Joined: Mar 22, 2012
Posts: 6
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

Joined: Apr 06, 2010
Posts: 4420
    
    8

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

Joined: Mar 22, 2012
Posts: 6
I got the concept. Thanks for the prompt reply.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: StackOverflowError when defining Instance of Class