Skip to the content.

채널 버퍼링

예제 91: 버퍼

이전에 만들었던 예제를 확장하여 버퍼를 지정해보자. Channel 생성자는 인자로 버퍼의 사이즈를 지정 받는다.

지정하지 않으면 버퍼를 생성하지 않는다.

import kotlinx.coroutines.* import kotlinx.coroutines.channels.* fun main() = runBlocking<Unit> { val channel = Channel<Int>(10) launch { for (x in 1..20) { println("${x} 전송중") channel.send(x) } channel.close() } for (x in channel) { println("${x} 수신") delay(100L) } println("완료") }

채널에 인자로 10을 지정했다. 10개까지는 수신자가 받지 않아도 계속 전송한다.

예제 92: 랑데뷰

버퍼 사이즈를 랑데뷰(Channel.RENDEZVOUS)로 지정해봅시다.

import kotlinx.coroutines.* import kotlinx.coroutines.channels.* fun main() = runBlocking<Unit> { val channel = Channel<Int>(Channel.RENDEZVOUS) launch { for (x in 1..20) { println("${x} 전송중") channel.send(x) } channel.close() } for (x in channel) { println("${x} 수신") delay(100L) } println("완료") }

랑데뷰는 버퍼 사이즈를 0으로 지정하는 것입니다. 생성자에 사이즈를 전달하지 않으면 랑데뷰가 디폴트입니다.

이외에도 사이즈 대신 사용할 수 있는 다른 설정 값이 있습니다.

예제 93: 버퍼 오버플로우

버퍼의 오버플로우 정책에 따라 다른 결과가 나올 수 있습니다.

import kotlinx.coroutines.* import kotlinx.coroutines.channels.* fun main() = runBlocking<Unit> { val channel = Channel<Int>(2, BufferOverflow.DROP_OLDEST) launch { for (x in 1..50) { channel.send(x) } channel.close() } delay(500L) for (x in channel) { println("${x} 수신") delay(100L) } println("완료") }