Here is a SizedStack type that extends Stack:

import java.util.Stack;

public class SizedStack<T> extends Stack<T> {
    private int maxSize;

    public SizedStack(int size) {
        super();
        this.maxSize = size;
    }

    @Override
    public T push(T object) {
        //If the stack is too big, remove elements until it's the right size.
        while (this.size() >= maxSize) {
            this.remove(0);
        }
        return super.push(object);
    }
}

Use it like this: Stack<Double> mySizedStack = new SizedStack<Double>(10);. Other than the size, it operates like any other Stack.

Answer from cal on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › jvm › configuring stack sizes in the jvm
Configuring Stack Sizes in the JVM | Baeldung
January 8, 2024 - For instance, these are some of the default sizes as of Java 14: ... Basically, we can expect around 1 MB for each stack in most modern operating systems and architectures. To change the stack size, we can use the -Xss tuning flag. For example, ...
🌐
AlphaCodingSkills
alphacodingskills.com › java › notes › java-stack-setsize.php
Java Stack setSize() Method - AlphaCodingSkills
The java.util.Stack.setSize() method is used to set the size of the stack. If the new size is greater than the current size, new null items are added to the top of the stack. If the new size is less than the current size, all components at index newSize and greater are discarded.
Discussions

java - Creating a fixed-size Stack - Stack Overflow
I want to create a Stack in Java, but fix the size. For example, create a new Stack, set the size to 10, then as I push items to the stack it fills up and when it fills up to ten, the last item in ... More on stackoverflow.com
🌐 stackoverflow.com
How to increase the Java stack size? - Stack Overflow
I got excited about this, but then .../docs/api/java/lang/Thread.html#Thread - the stacksize constructor - the excitement went away. 2013-12-09T13:53:42.463Z+00:00 ... I wonder which platforms are they when the document only say - "On some platforms" 2014-12-05T01:02:22.853Z+00:00 ... It is hard to give a sensible solution since you are keen to avoid all sane approaches. Refactoring one line of code is the senible solution. Note: Using -Xss sets the stack size of every thread ... More on stackoverflow.com
🌐 stackoverflow.com
StackOverflowError null, how can I increase the stacksize in the jvm
I'd be more concerned about why you're getting SOE, not with how to work around it. What does your thread do? More on reddit.com
🌐 r/javahelp
11
7
May 13, 2022
java - What is the default stack size, can it grow, how does it work with garbage collection? - Stack Overflow
Some Java Virtual Machines (JVM) put Java stack (Java method calls) and native stack (Native method calls in VM) into one stack, and perform stack unwinding using a "Managed to Native Frame", known as M2nFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Informatica
docs.informatica.com › common content for data engineering h2l › tuning the performance of the monitoring model repository › tuning the performance of the monitoring model repository › guidelines to improve the performance › tune the monitoring model repository › setting the java stack size property
Setting the Java Stack Size Property
The Java stack size is the size limit of each Java thread in the Java Virtual Machine (JVM) that runs the monitoring Model Repository Service. The default value is 512K. You can increase this property to make more memory available to monitoring Model Repository Service processes.
🌐
GeeksforGeeks
geeksforgeeks.org › java › stack-setsize-method-in-java-with-example
Stack setSize() method in Java with Example - GeeksforGeeks
December 24, 2018 - // Java program to demonstrate // setSize() method for String value import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // Creating object of Stack<Integer> Stack<String> stack = new Stack<String>(); // adding ...
🌐
Educative
educative.io › answers › what-is-the-stacksetsize-method-in-java
What is the Stack.setSize method in Java?
The element inserted first is processed last and the element inserted last is processed first. stack of objects. The setSize method changes the size of the Stack object.
🌐
Codeforces
codeforces.com › blog › entry › 166
Setting stack size in Java - Codeforces
Usually it's graph problems with big limitations which are solved by DFS. But deep recursion requires large stack size, often several megabytes. In C++ or Pascal/Delphi the stack size can be set by compiler directives. But it's impossible in Java.
Find elsewhere
🌐
Broadcom
knowledge.broadcom.com › external › article › 9482 › setting-jvm-threadstacksize-for-errorfre.html
Setting JVM ThreadStackSize for error-free Defects/Stats Aggregration operations.
June 3, 2026 - For most JVMs, setting the specified thread stack size to 192 (-XX:ThreadStackSize=192) for defects and statistical aggregation is sufficient, but there are JVMs which may need more than 256. All Supported APM Releases supporting APM CE (CEM). For the instructions below, obtain a copy of ...
🌐
javathinking
javathinking.com › blog › configuring-stack-sizes-in-the-jvm
Configuring Stack Sizes in the JVM: A Detailed Guide — javathinking.com
The primary way to set the stack size for every thread in the JVM is by using the -Xss command-line option. ... Example: To run a Java application MyApp.class with a stack size of 512 KB per thread, you would use:
🌐
ycrash Answers
answers.ycrash.io › question › what-is-java-stack-size--xss-
What is Java Stack Size: -Xss? - yCrash Answers
September 26, 2022 - The units can be specified as: ... an exact number of bytes, e.g. -Xss64 means just 64 bytes. ... The -Xss argument controls the size of the Java thread stack....
🌐
Reddit
reddit.com › r/javahelp › stackoverflowerror null, how can i increase the stacksize in the jvm
r/javahelp on Reddit: StackOverflowError null, how can I increase the stacksize in the jvm
May 13, 2022 -

Sorry, this might be a dumb question but I couldnt find anything about it in the internet. So I'm having the program run a thread, which turns out to be this error. I researched quite a bit and realized I need to change the StackSize, but I have no idea how to actually use the commands/arguments I found.

I'm using BlueJ and sadly I can't change to another software, so I'm stuck with what I think is the only option for bluej which is the bluej.defs file

Am I wrong here, can I use something else than the defs file? Idk thx for the answers in advance

🌐
Red Hat
access.redhat.com › solutions › 24094
How do I set Java thread stack size? - Red Hat Customer Portal
How to increase the stack size in order to avoid a java.lang.StackOverflowError. How to decrease stack size to save memory. How need to change the JVM stack size. How to set Java thread stack size on
🌐
GeeksforGeeks
geeksforgeeks.org › java › stack-size-method-in-java-with-example
Stack size() method in Java with Example - GeeksforGeeks
December 26, 2025 - It does not take any parameters and returns an int representing the stack's size. ... import java.util.*; public class GFG { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.add("Welcome"); stack.add("To"); stack.add("GFG"); System.out.println("Stack: " + stack); System.out.println("The size is: " + stack.size()); } }
Top answer
1 of 2
105

How much a stack can grow?

You can use a VM option named ss to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M to set the maximum of stack size to 1M.

Each thread has at least one stack. Some Java Virtual Machines (JVM) put Java stack (Java method calls) and native stack (Native method calls in VM) into one stack, and perform stack unwinding using a "Managed to Native Frame", known as M2nFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in most cases.

For many JVMs, they put different default values for stack size on different platforms.


Can we limit this growth?

When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In Java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in Java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on Java stack affects the performance some time (cache miss).


Does stack has some default minimum value or default maximum value?

As I said before, different VMs are different, and may change over versions. See here.


How does garbage collection work on stack?

Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.

This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .NET platform. The GC on Oracle JVM is quite similar so I think that might also help you.

2 of 2
16

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.
🌐
Mysoftkey
mysoftkey.com › data-structure-algorithm › how-to-implement-fixed-size-stack-in-java
How to Implement Fixed Size Stack in Java – mySoftKey
This method runs in O(1) time. public int pop() throws Exception { int data; if (isEmpty()) throw new NoSuchElementException("Stack is empty."); data = stack[top]; // dereference S[top] for garbage collection. stack[top--] = Integer.MIN_VALUE; return data; } @Override public int size() { return (top + 1); } @Override public boolean isEmpty() { return (top < 0); } /* * Returns a string representation of the stack as a list of elements, with * the top element at the end: [ prev, top ]. * * @see java.lang.Object#toString() */ @Override public String toString() { String s = "["; if (size() > 0) s += stack[0]; if (size() > 1) for (int i = 1; i <= size() - 1; i++) { s += ", " + stack[i]; } return s + "]"; } }
🌐
NetIQ
netiq.com › documentation › identity-manager-48 › identity_apps_admin › data › increasing-stack-size-for-tuning-identity-applications-workflow-performance.html
Increasing the Stack Size for Recursive Workflows - NetIQ Identity Manager - Administrator’s Guide to the Identity Applications
Therefore, you must increase the stack size for the JVM to 4M depending on the recursive logic defined in the workflow. To increase the stack size, define the new value in the -Xss setting in the JAVA_OPTS entry in your Tomcat start script file (/opt/netiq/idm/apps/tomcat/bin/setenv.sh or ...
🌐
Berksoftware
berksoftware.com › 23 › 12 › JVM-Stack-Memory
Can we optimize JVM stack size? | Berk Köprücü
December 6, 2023 - $ java -XX:+PrintFlagsFinal -version | grep -i threadstack intx CompilerThreadStackSize = 2048 intx ThreadStackSize = 2048 intx VMThreadStackSize = 2048 · ThreadStackSize : Stack size used by the application, can be set with ‘-Xss’ VMThreadStackSize : Native method stack size, can be set with -XX:VMThreadStackSize
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-configure-jvm-stack-sizes
How to Configure JVM Stack Sizes for Optimal Performance - CodingTechRoom
A. No, the stack size is set at the JVM level, not per thread. ... A broad desk reference for the Java language and standard library.
🌐
Ask Ubuntu
askubuntu.com › questions › 1251562 › how-to-adjust-java-stack-size-when-starting-a-java-executable
command line - How to adjust java stack size when starting a java executable? - Ask Ubuntu
June 18, 2020 - To check the default setting, I used the command "java -XX:+PrintFlagsFinal -version" and found the following entries related to stack size: