Sangil's blog

https://github.com/ChoiSangIl Admin

코틀린은 어떻게 Java에서 불변객체를 생성할 수 있게 만들었을까? DEV / PROGRAMING

2022-10-22 posted by sang12



“해당 그림으로는 이해가 안돼서 조금 더 뜯어 볼려고?한 이야기“

불변 리스트를 만드는 listOf 함수를 따라가 보자.

public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)

내부적으로 singletonList란 java collection 객체를 리턴 해주는 것을 볼 수 있다. singletonList 함수는 java Collections의 SingletonList<e> Class를 반환한다.
-java Collections.java → SingletonList class

 private static class SingletonList<E>
        extends AbstractList<E>
        implements RandomAccess, Serializable {

        @java.io.Serial
        private static final long serialVersionUID = 3093736618740652951L;

        @SuppressWarnings("serial") // Conditionally serializable
        private final E element;

        ... 생략 ....     
    }
        

여기서 SingletonList는 AbstracList<E>를 상속 받고 있는 것을 볼 수 있다. 어라? 그러면 add를 사용 할 수 있는거 아니야? 라는 의문이 들었다.

직접 사용해보자!

fun main(){
    val americano = Coffee("americano", 5000)
    val mix = Coffee("mix", 300)
    val espresso = Coffee("espresso", 4000)

    //public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
    val list : List<Coffee> = java.util.Collections.singletonList(americano);
    //list.add() 사용 못함

    var list2 = java.util.Collections.singletonList(americano);
    //list2.add(mix)  //호출가능 하지만 오류가남 listOf는 넘겨주는 객체가 1개일 때는 singletonList를 사용하기 때문에 오류 발생 java singletonList = 인덱스가 1개일인 리스트
}

data class Coffee(
    val name : String,
    val price : Int
)

ArrayList를 사용하는 Immutable List를 선하고 자바 클래스 타입을 찍어보면java.util.Arrays$ArrayList을 사용하는 것을 알 수 있다. 하지만 add를 사용할 수 없다(왜일까? - 뒤에..).

그렇다면 직접 자바의 asList를 만들어서 사용해보자. 그럼 add의 호출은 가능하나 컴파일 시점에서 오류가 난다. 코틀린에서 immutable list에서 여러개의 인자로 리스트를 만들 때 코틀린에서 내부적으로 asList를 이용해 객체를 생성하기 때문에 그렇다. (java의 asList 특성)

fun main(){
    //여러개의 값을 받는 리스트 선언
    val list3 : List<Coffee> = listOf(americano, mix)
    println("${list3.javaClass} $list3") // 출력결과 : class java.util.Arrays$ArrayList [Coffee(name=americano, price=5000), Coffee(name=mix, price=300)] 내부적으로 java ArrayList를 사용하는 것을 알 수 있다.
    //list3.add(espresso) 역시 사용 못함

    val list4 = java.util.Arrays.asList(americano, mix)
    println("${list4.javaClass} $list4")
    //list4.add(espresso) 호출은 가능하지만 오류가남 java의 asList 특성
}

data class Coffee(
    val name : String,
    val price : Int
)

어떻게 코틀린에서는 내부적으로 Java Class를 사용하면서, add 함수를 사용 못하게 만들었을까?
- kotlin lostOf function

public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
-> val list : List<Coffee> = java.util.Collections.singletonList(americano);

정답은 이 부분에 있는거 같다. 자바의 java.util.Collections.singletonList 객체를 코틀린 List<T> 타입의 형태로 반환 해준다

fun main(){
    //여러개의 값을 받는 리스트 선언
    val list3 : List<Coffee> = listOf(americano, mix)
    println("${list3.javaClass} $list3") // 출력결과 : class java.util.Arrays$ArrayList [Coffee(name=americano, price=5000), Coffee(name=mix, price=300)] 내부적으로 java ArrayList를 사용하는 것을 알 수 있다.
    //list3.add(espresso) 역시 사용 못함

    val list4 = java.util.Arrays.asList(americano, mix)
    println("${list4.javaClass} $list4")
    //list4.add(espresso) 호출은 가능하지만 오류가남 java의 asList 특성
}

data class Coffee(
    val name : String,
    val price : Int
)

어떻게 코틀린에서는 내부적으로 Java Class를 사용하면서, add 함수를 사용 못하게 만들었을까?
- kotlin lostOf function

public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
-> val list : List<Coffee> = java.util.Collections.singletonList(americano);

정답은 이 부분에 있는거 같다. 자바의 java.util.Collections.singletonList 객체를 코틀린 List<T> 타입의 형태로 반환 해준다

어떻게 Java 클래스가 코틀린 타입으로 리턴 받을 수 있을까?
→ 코틀린도 결국 Java로 변환 되니 Java의 List와 호환되는 인터페이스로 변환이 되는걸까?
(코틀린에서 Java에 호환되는 인터페이스를 만들어서 사용해보자 요걸 해보면 좀 더 이해가 쉽지 않을까 싶다.. 다음에 해보자 )

처음에 해당 사항이 궁금해서 리서치 중, 코틀린의 List 인터페이스의 구현체가 없을까? 라는 생각으로 접근 했었습니다. 그러다가 찾은 js에서의 ArrayList 구현체.
https://github.com/JetBrains/kotlin/blob/f3385fbdcb8b9dc29661a8a4973c855cdcf73767/libraries/stdlib/js/src/kotlin/collections/ArrayList.kt#L15

kotlin의 List 인터페이스를 보면 add가 없는 것을 볼 수 있다.
결국 코틀린은 Java의 List를 사용하나 코틀린 인터페이스에서 이를 제공해주지 않아서 사용 할 수 없게 만들어 불변(immutable)을 지킨다고 볼 수 있다.

-Collections.kt

public interface List<out E> : Collection<E> {
    // Query Operations

    override val size: Int
    override fun isEmpty(): Boolean
    override fun contains(element: @UnsafeVariance E): Boolean
    override fun iterator(): Iterator<E>

    // Bulk Operations
    override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean

    // Positional Access Operations
    /**
     * Returns the element at the specified index in the list.
     */
    public operator fun get(index: Int): E

    ....생략 ....
}
REPLY

코루틴이 정녕 무엇입니까 (코루틴 기본 Basic 6선으로 알아보자) DEV / PROGRAMING

2022-10-12 posted by sang12


  • 참고 사이트

https://github.com/Kotlin/kotlinx.coroutines

https://kotlinlang.org/docs/coroutines-basics.html#your-first-coroutine

Gradle Setting

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
runtimeOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-slf4j:1.6.4")


실습할 때 설정하면 좋은 것

pinrtln 정의

fun <T>println(msg: T) = kotlin.io.println("$msg [${Thread.currentThread().name}]")

jvm option 추가

-Dkotlinx.coroutines.debug


실습으로 배우자

“코틀린 공식사이트 예제 6선(https://github.com/Kotlin/kotlinx.coroutines)“

01.

import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello") // main coroutine continues while a previous one is delayed
}

결과

Hello [main @coroutine#1]
World! [main @coroutine#2]

“main Thread는 runBlocking을 만나고 CoroutineScope 실행한다. 이때, launch라는 코루틴을 만나고 1초간 Delay된다(어라 블락킹 되지 않네?). 이후 메인 쓰레드는 launch를 탈출하고 Hello를 찍고, 1초후 다시 중단되었던 launch로 돌아가 World를 출력한다“

02.

import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    launch { doWorld() }
    println("Hello")
}

// this is your first suspending function
suspend fun doWorld() {
    delay(1000L)
    println("World!")
}

결과

Hello [main @coroutine#1]
World! [main @coroutine#2]

“아.. 이제 function으로 분리를 하고 싶나보다. 이때 suspend를 사용하지 않으면 delay에서 오류가 난다. 왜일까? delay는 내부적으로 suspend fun으로 되어있고 해당 function은 코루틴 스코프 안에서만 사용 할 수 있는거 같다. 그래서 delay를 사용하려면 suspend fun으로 생성해줘야 한다. 결과는 01과 다를게 없다. 다만 함수로 분리가 되었을 뿐“

03.

fun main() = runBlocking {
    doWorld()
}

suspend fun doWorld() = coroutineScope {  // this: CoroutineScope
    launch {
        delay(1000L)
        println("World!")
    }
    println("Hello")
}

결과

Hello [main @coroutine#1]
World! [main @coroutine#2]

“이제 그냥 다 분리하고 싶나 보다. 결과는 똑같다. 메인 Thread는 runBlocking을 만나 doWorld() 라는 코루틴 스코프를 실행한다. 당연하게도 해당 스레드는 launch의 delay를 만나면 블락킹되지 않고 Hello를 출력한다.“

04.

import kotlinx.coroutines.*

// Sequentially executes doWorld followed by "Done"
fun main() = runBlocking {
    doWorld()
    println("Done")
}

// Concurrently executes both sections
suspend fun doWorld() = coroutineScope { // this: CoroutineScope
    launch {
        delay(2000L)
        println("World 2")
    }
    launch {
        delay(1000L)
        println("World 1")
    }
    println("Hello")
}

“오.. 드디어 Hello world에서 벗어났다. 이제 한번 결과 값을 예측해보고 정답을 보기로 하자 “

결과

Hello [main @coroutine#1]
World 1 [main @coroutine#3]
World 2 [main @coroutine#2]
Done [main @coroutine#1]

“메인 Thread는 runBlocking과 만나 코루틴에 진입한다. doWorld라는 suspend함수를 실행하고 launch의 delay를 만나서 해당 launch는 탈출하고 다음을 실행한다. 다음 루틴에서 delay(1000)을 만나서 또 탈출하고 Hello를 출력한다. 그리고 해당 코루틴 스코프의 남은 작업들 World1, World2를 출력하고 해당 코루틴을 탈출하여 Done이란 문자열을 출력한다.“

여기서 알 수 있는 점은 doWorld() 라는 suspend 코루틴 스코프가 끝나야 Done이라는 문자열을 출력한다는 것이다.

05.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch { // launch a new coroutine and keep a reference to its Job
        delay(1000L)
        println("World!")
    }
    println("Hello")
    job.join() // wait until child coroutine completes
    println("Done") 
}

결과

Hello [main @coroutine#1]
World! [main @coroutine#2]
Done [main @coroutine#1]

“Join이란 친구가 등장 했다. 그리고 launch블락을 job이란 val에 담고 있는 모습을 볼 수 있다. 실행 결과를 보면 알 수 있듯이 job이 끝난후에 Done이라는 문자열이 출력되는 것을 볼 수 있다.“

여기서 알 수 있는 점은 join을 사용하면 해당 코루틴을 수행하는 Thread는 해당 job이 종료 될때까지 기다렸다가 다음 루틴을 수행한다는 것이다.

06

import kotlinx.coroutines.*

fun main() = runBlocking {
    repeat(100_000) { // launch a lot of coroutines
        launch {
            delay(5000L)
            print(".")
        }
    }
}

결과

................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................

코루틴을 자랑하기 위해 넣어놓은 예제 같다.

“코루틴은 왜? 경량 쓰레드인가요!?” 라고 구글링하면 해당 예제들이 많이 나온다.

이 때 해당 로직을 Java의 Thread를 사용하여 구현했을 때와 많이 비교하는데, 코루틴은 무려 이 작업을 1개의 Thread로 수행한다. 만약 이 작업을 Java Thread로 구현한다면. 얼마나 많은 자원이 들까? 환경에 따라 OOM이 날수도 있을거 같다.

공부하면서 궁금했던 점

delay대신 Thread.sleep이 들어가면 어떻게 될까?

bart-test-01

fun main() = runBlocking {
    count()
    println("Done")
}

suspend fun count() = coroutineScope {
    launch {
        repeat(5){i ->
            delay(1000L)
            println("Coroutine A, $i")
        }
    }

    launch {
        repeat(5){i ->
            delay(1000L)
            println("Coroutine B, $i")
        }
    }

    println("Coroutine Outer")
}

결과

Coroutine Outer [main]
Coroutine A, 0 [main]
Coroutine B, 0 [main]
Coroutine A, 1 [main]
Coroutine B, 1 [main]
Coroutine A, 2 [main]
Coroutine B, 2 [main]
Coroutine A, 3 [main]
Coroutine B, 3 [main]
Coroutine A, 4 [main]
Coroutine B, 4 [main]
Done [main]

bart-test-01을 실행하면 결과값은 위와 같다.

delay를 만나 2개의 launch루틴을 탈출하고 Coroutin Outer가 먼저 출력된다.

그리고 사이좋게 A, B가 실행 되는 것을 볼 수 있다

하지만 Thread.sleep을 사용하면 어떻게 될까?

bart-test-02

fun main() = runBlocking {
    count()
    println("Done")
}

suspend fun count() = coroutineScope {
    launch {
        repeat(5){i ->
            Thread.sleep(1000)
            println("Coroutine A, $i")
        }
    }

    launch {
        repeat(5){i ->
            Thread.sleep(1000)
            println("Coroutine B, $i")
        }
    }

    println("Coroutine Outer")
}

결과

Coroutine Outer [main]
Coroutine A, 0 [main]
Coroutine A, 1 [main]
Coroutine A, 2 [main]
Coroutine A, 3 [main]
Coroutine A, 4 [main]
Coroutine B, 0 [main]
Coroutine B, 1 [main]
Coroutine B, 2 [main]
Coroutine B, 3 [main]
Coroutine B, 4 [main]
Done [main]

메인 thread는 2개의 launch 루틴을 셋팅하고 Coroutine Outer를 먼저 출력 하는거 같다. ( 사실 첫번째 sleep에 블락킹 되어서 먼저 않나오지 않을까? 라고 생각 했는데.. )

그리고 메인 쓰레드는 루틴을 실행하며 이리저리 루틴을 뛰어 넘어 다녀야 할 녀석인데 Thread.sleep을 만나고 블락킹 되어서 A루틴에서 빠져 나가지 못하는 모습을 보여준다. 결국 A루틴이 끝이나야 B루틴을 실행하는 모습을 볼 수 있다.

결론

코루틴 스코프에서 메인 Thread가 블락되는 상황이 발생하면 성능에 좋지 못한 결과를 얻을 수 있다(예상치 못한 결과)

그리고 더 공부해야한다. 기본 샘플 6개를 봤을 뿐…

REPLY
REPLY