Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

thread lambda expression in Kotlin

Sample code:

fun main() {
   thread(name = "Worker Thread") {
        for (i in 1..5) {
            println(Thread.currentThread().name)
        }
    }
    println(Thread.currentThread().name)
}

Decompiled bytecode for the above sample:

public final class PracKt {
   public static final void main() {
      ThreadsKt.thread$default(false, false, (ClassLoader)null, "Worker Thread", 0, (Function0)null.INSTANCE, 23, (Object)null);
      Thread var10000 = Thread.currentThread();
      Intrinsics.checkNotNullExpressionValue(var10000, "Thread.currentThread()");
      String var0 = var10000.getName();
      boolean var1 = false;
      System.out.println(var0);
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }
}

Code works fine but I can’t understand in decompiled code how thread gets executed without calling start() method. If I try to call thread.start() in sample code, IllegalThreadStateException is thrown.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Where is start() method is getting called if not shown in decompiled code?

>Solution :

As it goes from Kotlin docs. When you’re using method thread, created thread is started by default.

fun thread(
    start: Boolean = true,
    isDaemon: Boolean = false,
    contextClassLoader: ClassLoader? = null,
    name: String? = null,
    priority: Int = -1,
    block: () -> Unit
): Thread

To start it explicitly, you should set start flag to false.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading