Using -Xss to adjust Java default thread stack size to save memory and prevent StackOverflowError

Every thread created in a Java program has its own stack space. The stack space used is not allocated from the heap. Infact if you look at the OS report on the memory used by your JVM, you may notice that it is more than what -Xmx parameter specifies. This is because, beside other things, memory is used for the thread stacks too. And this memory is not included in the heap specified by the -Xms and -Xmx switches.

The thread stack is used to push stacks frames in nested method calls. If the nesting is so deep that the thread runs out of space, the thread dies with a StackOverflowError.

The default thread stack size varies with JVM, OS and environment variables. A typical value is 512k. It is generally larger for 64bit JVMs because references are 8 bytes rather than 4 bytes in size. This means that if your app uses 150 threads, 75MB will be used for thread stacks. In some environments the defaults stack may be as large as 2MB. With a large number of threads, this can consume a significant amount of memory which could otherwise be used by your application or OS.

In most applications, 128k happens to be enough for the stack. What you really need to do is adjust and observe. If you don’t see your app running out of stack space, use the -Xss JVM parameter to specify a smaller stack (-Xss128k).

Note that it is entirely possible that your OS rounds up values for stack size specified by your -Xss parameter. Watch out for that.

Using the program below, you can see how stack space is used up by methods with varying number of arguments. You’ll get the StackOverflowError with fewer nested method calls for a smaller stack. You could try adjusting the number of arguments and even the type of arguments for different behaviour.

By adjusting the stack size, and keeping the code the same, you can see the JVM dying at different points in the recursive call.



Tags: ,
This entry was posted on Thursday, February 17th, 2011 at 5:19 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

32 Responses to “Using -Xss to adjust Java default thread stack size to save memory and prevent StackOverflowError”

  1. Ilias Tsagklis

    Hi Onkar,

    Very interesting blog! Is there an email address I can contact you in private?

  2. Hareesh

    Hi Nice Answers… Can I get in touch with you Onkar?

  3. vikas

    Short and precise explanation. Thank you for the info …

  4. Bappaditya

    Very well explained….

  5. Kondal

    Nice write up!!

  6. srikanth

    Thanks for explaining in short. very good article and very useful

  7. Binh Thanh Nguyen

    Thanks, nice post

  8. Sekhar

    Hi Onkar,

    I am having some issue with this -Xss parameter of JVM, I am using 1.7.72 jre in Linux & windows. I am using -Xss as 128K which is working in almost all windows family. In Ubuntu we faced strange issue. The same configurations are working in Ubuntu 11 in 32 & 64 bits. In Ubuntu-14 64 bit machine we are getting an error saying that minimum Xss value should be 228K. If this is JRE wide parameter then in different OS flavors why we will get an error? is this parameter will play vital role in various OS flavors?

  9. free it disposal portsmouth

    A few things i have seen in terms of computer memory is that there are technical specs such as SDRAM, DDR and many others, that must fit the specs of the motherboard. If the personal computer’s motherboard is kind of current while there are no os issues, upgrading the storage space literally normally takes under one hour. It’s one of the easiest pc upgrade processes one can picture. Thanks for revealing your ideas.

  10. it asset recycling oxford

    The things i have observed in terms of computer memory is that often there are technical specs such as SDRAM, DDR and the like, that must fit in with the specifications of the mother board. If the personal computer’s motherboard is very current while there are no computer OS issues, improving the memory space literally usually takes under an hour. It’s among the list of easiest computer upgrade treatments one can visualize. Thanks for discussing your ideas.

  11. Neuromax Side Effects

    Hi there to every body, it’s my first go to see of this blog; this website includes
    awesome and genuinely fine information designed for readers.

  12. Ghost Writer

    Essays are about writing style and grammar, but dissertations are not.
    There are many web content writing services worldwide.
    A good writing service will employ only the most qualified, experienced and expert writers.

  13. kurusal site

    Yazınız için çok teşekkür ederim

  14. Responsive Web Design Miami

    Thanks for every other informative site. Where else may I am getting that
    kind of info written in such an ideal approach? I’ve a mission that I am just now working on, and I’ve been at the
    glance out for such information.

  15. https://www.google.es/

    Si pensamos en un sofá relax para un interior de inspiración escandinava, la
    primera firma que nos viene a la cabeza es la Sueca
    Ikea.

  16. Muay Thai Training camp

    My partner and I absolutely love your blog and find the majority of your post’s to be
    just what I’m looking for. Would you offer guest writers to write content for you personally?
    I wouldn’t mind producing a post or elaborating on
    a lot of the subjects you write regarding here. Again, awesome weblog!

  17. john edward

    In fact, many of them have their names advertised and their calling cards
    passed around. The practices date back millennia though and are found in many of the great civilisations.
    – The word clairvoyance means clear seeing and is often referred to as the ‘sixth sense’.

  18. Geraldo

    Me ha gustado tu post. Hace por lo menos 4 meses que sufro
    lo mismo. Me he sentido identificada.

  19. รูป ธงชาติ ไทย แบบ ต่างๆ

    This is really interesting, You’re an overly skilled blogger.
    I have joined your rss feed and sit up for looking for more of your magnificent post.
    Also, I’ve shared your web site in my social networks

  20. Michelle

    What power would you like to see in League of Legends. The one class that is probably entirely simplified for gameplay within Allods Online is the Summoner class.
    It’s been more than a decade but I still remember it to be the best RPG I’ve ever played.

  21. jordan air

    DareToFly rise JORDAN AGENCY! Into the last half at shoes and
    boots, compared to what had been in tint; as well as st. Patrick’s time, our own league happens
    to be greenish found on the…

  22. Theron

    The amount of yur monthly obligations is only a parameter of the loan. The EPA
    released the fuel-economy numbers and there is certainly nno
    challenge that hybrids far out-distance some other car for fuel-efficiency.
    As yyou will note later, there is still a bonus to doing all your auto shopping following the
    month.

  23. mieszkania

    Having read this I believed it was rather enlightening.
    I appreciate you spending some tme and effort to put this information together.

    I once aagain find myself spending a lot of time both reading and leavingg
    comments. But soo what, it was still worthwhile!

  24. edenspadownhall.co.uk

    As mentioned above, site load time is an element and the two finest tools
    I have actually used to reduce image file sizes are Adobe
    Photoshop and Adobe Fireworks – undoubtedly Fireworks did the
    slightly much better job, despite the fact that it was
    just a couple of kilobytes.

  25. проститутки в Москве

    What’s up, just wanted to tell you, I enjoyed this post.
    It was helpful. Keep on posting!

  26. seo canada

    Thanks for revealing your ideas. One thing is that college students have an alternative between federal government student loan as well as a private student loan where its easier to select student loan consolidating debts than in the federal student loan.

  27. seo franchise

    One thing is that if you are searching for a education loan you may find that you’ll need a co-signer. There are many conditions where this is true because you will find that you do not use a past credit score so the bank will require that you have someone cosign the money for you. Interesting post.

  28. Carrie

    Be sure that you keep your daily routine
    force, chi. This approach is really significant. Assure to trust the potency of
    thoughts. Don’t attempt vulgar verbiage in addition to activities.

  29. what is a good fico score

    Definitely imagine that that you said. Your favourite justification seemed to be on the net
    the simplest thing to consider of. I say to you, I certainly
    get annoyed at the same time as other folks consider worries that they plainly do
    not know about. You managed to hit the nail
    upon the highest and defined out the whole thing with no need side effect , other folks can take a
    signal. Will probably be back to get more. Thanks

  30. sergeysoschi1100998

    Наша ООО «Инжгеосервис» предлагает услуги изготовления проектов водоснабжения и канализации.
    Мы – это качество. Мы – это инжиниринг высокого уровня. С нами вы экономите в 3 раза (в Водоканале проект стоит минимум от 50 т.р.)
    Наши телефоны: 8-928-665-0035
    От Вас:

    – топосъемка M1:500
    – паспорт
    – технические условия
    Срок 5 дней. Результат – проект под ключ!
    Мы находимся в Сочи, работаем по всем районам города.

  31. benq

    I got this web page from my pal who informed me
    about this web site and now this time I am browsing this site
    and reading very informative articles at this time.

  32. Brigitte Moyes

    “Hosting”

Leave a Reply

Your comment