/kotlin-concurrency-demo

Kotlin Concurrency Examples

Primary LanguageKotlin

Kotlin Concurrency Examples

This project provides small examples that illustrate different aspects of Kotlin's Concurrency Support.

Coroutines

Coroutines is a lightweight concurrency framework. A Coroutine defines an asynchronous unit of work. Unlike Native Threads, a Coroutine is not bound to a particular thread - it can be started/started and assigned to different threads. The Coroutine is typically invoked using the launch keyword and returns an instance of a Job that allows you to either cancel or wait for completion. A Job is unable to return a value.

  • CoroutineExample illustrates an invocation of a suspending function within a Coroutine.

Channel

Kotlin Coroutines can use Channels to transmit data between Coroutines and the larger context.

  • AutoCloseChannelExample demonstrates creating, transmitting, and auto-closing a Channel at the conclusion of the Coroutine.

Async/Await

Kotlin's async/await allows for a Coroutine to return a value.

  • AsyncExample demonstrates the speed improvements of concurrency and shows a Coroutine wrapped in an async invocation that returns a value.

Flow

Kotlin's flow and channelFlow framework provides the ability for a Coroutine to transmit an interruptible stream of data.

Shared State

Kotlin supports protecting shared state using the Mutex class for Coroutines and the @Synchronized Annotation for Native Threading

  • MutexExample demonstrates using the Mutex Class to synchronize state access within a Coroutine.
  • SynchronizedStateExample demonstration using the @Synchronized annotation to synchronize state access within Native Threading.

Running the Demo

From the command line, issue ./gradlew run.