Encyclopedia
Encyclopedia

Reputation: 144

How to set stack size of main Thread

In case of java we have JVM parameter -Xss which sets the stack Size for a particular Thread.

We can set this parameter as JVm argument or specify it in Thread Constructor like:-

Thread(ThreadGroup group, Runnable target, String name, long stackSize)

This will allocate a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

But how to set the stack size of main method which is running. Ideally main method is also in itself a thread , so how do we specify its stack size explicitly apart from using -Xss parameter ?

Upvotes: 0

Views: 1624

Answers (4)

Gray
Gray

Reputation: 116918

But how to set the stack size of main method which is running. Ideally main method is also in itself a thread , so how do we specify its stack size explicitly apart from using -Xss parameter ?

The -Xss parameter affects the main stack size as well. You don't need to do anything special to set it. If you really asking if you can set the main stack size separate from the -Xss parameter, you can't.

For example, you can set the -Xss parameter and see more or less stack overflow exception lines:

public class Foo {
    public static void main(String[] args) {
        foo();
    }
    private static void foo() {
        foo();
    }
}

-Xss=128k gives ~444 lines while 256k gives ~1025 lines.

Upvotes: 2

Ingo
Ingo

Reputation: 36339

-Xss is exactly the way to do it. It tells the runtime exactly the long stackSize parameter to use when creating your main thread.

However, you can't change the stacksize of already existing threads, so the only thing you can do is to create your own "main" thread! Remember, the ordinary "main" thread is not special in anything. Just fire up another thread and let it run your main program, then finish the JVM-main thread.

Upvotes: 3

codingenious
codingenious

Reputation: 8663

main thread is user thread, but a special thread. Stack size can not be specified for main thread individually. Either you specify -Xss for all threads or for a particular thread on creation.

Note possible for main, as this is not created by user but by JVM.

Upvotes: 1

Taylor
Taylor

Reputation: 4086

how do we specify [main thread's] stack size explicitly apart from using -Xss parameter ?

You can't. It needs to be specified on thread creation and the only way to do that is with jvm args.

Upvotes: 1

Related Questions