Survive from Stack Overflow in Kotlin

Правка en4, от liouzhou_101, 2020-05-19 19:48:11

DFS is commonly used in those problems about trees and graphs. However, an unpopular guy — STACK OVERFLOW — often appears.

The issue about the size of the stack is discussed here. However, only a few languages have been discussed there. For example, in CodeForces platform, the stack size of C/C++ is 256MB, while, that of JAVA is poorly 64MB. MikeMirzayanov said he would change it but it seems he forgot it (or at least the stack overflow issue is not resolved for every language). Fortunately, at least there is a solution for JAVA with threads. Why threads? It seems there is the only way to set stack size at the code (against compile) level in JAVA. Moreover, thanks to CodeForces that threads (in JAVA) have not been banned so far.

The Kotlin Heroes Episode will be held in a few days. While I am using Kotlin, the STACK OVERFLOW issue comes out. It seems there is no blog that talks about this issue at least at this moment. I have struggled for it for days and fortunately resolve it finally. I'd like to share the solution with you, and hope it will help for you.

I first noticed that Kotlin could use JAVA libraries in Petr's code in Kotlin Heroes Episode 1. I combine Kotlin code with the previous solution to stack size for JAVA, and then find that it really works. Since there is still a little difference between Kotlin and JAVA, it is necessary to post the Kotlin code below.

import java.util.*

fun main()
    Thread(null, Main(), "whatever", 1 shl 28).start()

class Main : Runnable
    override fun run()
        // Treat this function as main function and do whatever you want
        // Say goodbye to STACK OVERFLOW

I'd like to note that the constant 1 shl 28 indicates the size of stack being 256MB.

I am not very familiar to Kotlin. If there is a better way to do this, please share with us.

Теги kotlin, stack, thread


  Rev. Язык Кто Когда Δ Комментарий
en4 Английский liouzhou_101 2020-05-19 19:48:11 467 Tiny change: 'g 256MB.\nI am not' -> 'g 256MB.\n\nI am not' (published)
en3 Английский liouzhou_101 2020-05-19 19:35:03 247
en2 Английский liouzhou_101 2020-05-19 19:32:21 683
en1 Английский liouzhou_101 2020-05-19 19:12:28 741 Initial revision (saved to drafts)