What is the android UI thread stack size limit and how to overcome it?

I believe that the main thread’s stack is controlled by the JVM – in Android’s case – Dalvik JVM. The relevant constant if I’m not mistaken is found in dalvik/vm/Thread.h under #define kDefaultStackSize

Browsing for stack sizes through the dalvik source history:

  • API 3 (Android 1.5) = 8KB

  • API 4-10 (Android 1.6 – Android 2.3.7) = 12KB

  • API 14-17 (Android 4.0 – Android 4.2.2) = 16KB

So how many nested views can you have:

Impossible to say accurately. Assuming the stack sizes are as described above, it all depends on how many function calls you have in your deepest nesting (and how many variables each function takes, etc). It seems that the problematic area is when the views are being drawn, starting with android.view.ViewRoot.draw(). Each view calls the draw of its children and it goes as deep as your deepest nesting.

I would perform empirical tests at least on the devices appearing in all the boundary groups above. It seems that using the emulator gives accurate results (although I’ve only compared the native x86 emulator to a real device).

Keep in mind that optimizations to how the actual widgets / layouts are implemented may also influence this. Having said that, I believe that most of the stack space is eaten by every layout hierarchy adding about 3 nested function calls: draw() -> dispatchDraw() -> drawChild() and this design hasn’t changed much from 2.3 – 4.2.

Leave a Comment