• Stars
    star
    716
  • Rank 63,241 (Top 2 %)
  • Language
    Kotlin
  • License
    Other
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The idiomatic way to use atomic operations in Kotlin

AtomicFU

Kotlin Beta JetBrains official project GitHub license Maven Central

Note on Beta status: the plugin is in its active development phase and changes from release to release. We do provide a compatibility of atomicfu-transformed artifacts between releases, but we do not provide strict compatibility guarantees on plugin API and its general stability between Kotlin versions.

Atomicfu is a multiplatform library that provides the idiomatic and effective way of using atomic operations in Kotlin.

Table of contents

Requirements

Starting from version 0.22.0 of the library your project is required to use:

  • Gradle 7.0 or newer

  • Kotlin 1.7.0 or newer

Features

  • Code it like a boxed value atomic(0), but run it in production efficiently:
    • as java.util.concurrent.atomic.AtomicXxxFieldUpdater on Kotlin/JVM
    • as a plain unboxed value on Kotlin/JS
  • Multiplatform: write common Kotlin code with atomics that compiles for Kotlin JVM, JS, and Native backends:
    • Compile-only dependency for JVM and JS (no runtime dependencies)
    • Compile and runtime dependency for Kotlin/Native
  • Use Kotlin-specific extensions (e.g. inline loop, update, updateAndGet functions).
  • Use atomic arrays, user-defined extensions on atomics and locks (see more features).
  • Tracing operations for debugging.

Example

Let us declare a top variable for a lock-free stack implementation:

import kotlinx.atomicfu.* // import top-level functions from kotlinx.atomicfu

private val top = atomic<Node?>(null) 

Use top.value to perform volatile reads and writes:

fun isEmpty() = top.value == null  // volatile read
fun clear() { top.value = null }   // volatile write

Use compareAndSet function directly:

if (top.compareAndSet(expect, update)) ... 

Use higher-level looping primitives (inline extensions), for example:

top.loop { cur ->   // while(true) loop that volatile-reads current value 
   ...
}

Use high-level update, updateAndGet, and getAndUpdate, when possible, for idiomatic lock-free code, for example:

fun push(v: Value) = top.update { cur -> Node(v, cur) }
fun pop(): Value? = top.getAndUpdate { cur -> cur?.next } ?.value

Declare atomic integers and longs using type inference:

val myInt = atomic(0)    // note: integer initial value
val myLong = atomic(0L)  // note: long initial value   

Integer and long atomics provide all the usual getAndIncrement, incrementAndGet, getAndAdd, addAndGet, and etc operations. They can be also atomically modified via += and -= operators.

Quickstart

Apply plugin

Gradle configuration

Gradle configuration is supported for all platforms, minimal version is Gradle 6.8.

In top-level build file:

Kotlin
buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
      classpath("org.jetbrains.kotlinx:atomicfu-gradle-plugin:0.22.0")
    }
}

apply(plugin = "kotlinx-atomicfu")
Groovy
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.jetbrains.kotlinx:atomicfu-gradle-plugin:0.22.0'
    }
}
  
apply plugin: 'kotlinx-atomicfu'

Maven configuration

Maven configuration is supported for JVM projects.

Declare atomicfu version
<properties>
     <atomicfu.version>0.22.0</atomicfu.version>
</properties> 
Declare provided dependency on the AtomicFU library
<dependencies>
    <dependency>
        <groupId>org.jetbrains.kotlinx</groupId>
        <artifactId>atomicfu</artifactId>
        <version>${atomicfu.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Configure build steps so that Kotlin compiler puts classes into a different classes-pre-atomicfu directory, which is then transformed to a regular classes directory to be used later by tests and delivery.

Build steps
<build>
  <plugins>
    <!-- compile Kotlin files to staging directory -->
    <plugin>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-maven-plugin</artifactId>
      <version>${kotlin.version}</version>
      <executions>
        <execution>
          <id>compile</id>
          <phase>compile</phase>
          <goals>
            <goal>compile</goal>
          </goals>
          <configuration>
            <output>${project.build.directory}/classes-pre-atomicfu</output>
          </configuration>
        </execution>
      </executions>
    </plugin>
    <!-- transform classes with AtomicFU plugin -->
    <plugin>
      <groupId>org.jetbrains.kotlinx</groupId>
      <artifactId>atomicfu-maven-plugin</artifactId>
      <version>${atomicfu.version}</version>
      <executions>
        <execution>
          <goals>
            <goal>transform</goal>
          </goals>
          <configuration>
            <input>${project.build.directory}/classes-pre-atomicfu</input>
            <!-- "VH" to use Java 9 VarHandle, "BOTH" to produce multi-version code -->
            <variant>FU</variant>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Usage constraints

  • Declare atomic variables as private val or internal val. You can use just (public) val, but make sure they are not directly accessed outside of your Kotlin module (outside of the source set). Access to the atomic variable itself shall be encapsulated.
  • To expose the value of an atomic property to the public, use a delegated property declared in the same scope (see atomic delegates section for details):
private val _foo = atomic<T>(initial) // private atomic, convention is to name it with leading underscore
public var foo: T by _foo            // public delegated property (val/var)
  • Only simple operations on atomic variables directly are supported.
    • Do not read references on atomic variables into local variables, e.g. top.compareAndSet(...) is ok, while val tmp = top; tmp... is not.
    • Do not leak references on atomic variables in other way (return, pass as params, etc).
  • Do not introduce complex data flow in parameters to atomic variable operations, i.e. top.value = complex_expression and top.compareAndSet(cur, complex_expression) are not supported (more specifically, complex_expression should not have branches in its compiled representation). Extract complex_expression into a variable when needed.

Transformation modes

Basically, Atomicfu library provides an effective usage of atomic values by performing the transformations of the compiled code. For JVM and JS there 2 transformation modes available:

  • Post-compilation transformation that modifies the compiled bytecode or *.js files.
  • IR transformation that is performed by the atomicfu compiler plugin.

Atomicfu compiler plugin

Compiler plugin transformation is less fragile than transformation of the compiled sources as it depends on the compiler IR tree.

To turn on IR transformation set these properties in your gradle.properties file:

For Kotlin >= 1.7.20
kotlinx.atomicfu.enableJvmIrTransformation=true // for JVM IR transformation
kotlinx.atomicfu.enableJsIrTransformation=true // for JS IR transformation
For Kotlin >= 1.6.20 and Kotlin < 1.7.20
kotlinx.atomicfu.enableIrTransformation=true // only JS IR transformation is supported

Also for JS backend make sure that ir or both compiler mode is set:

kotlin.js.compiler=ir // or both

Options for post-compilation transformation

Some configuration options are available for post-compilation transform tasks on JVM and JS.

To set configuration options you should create atomicfu section in a build.gradle file, like this:

atomicfu {
  dependenciesVersion = '0.22.0'
}

JVM options

To turn off transformation for Kotlin/JVM set option transformJvm to false.

Configuration option jvmVariant defines the Java class that replaces atomics during bytecode transformation. Here are the valid options:

  • FU – atomics are replaced with AtomicXxxFieldUpdater.
  • VH – atomics are replaced with VarHandle, this option is supported for JDK 9+.
  • BOTH – multi-release jar file will be created with both AtomicXxxFieldUpdater for JDK <= 8 and VarHandle for JDK 9+.

JS options

To turn off transformation for Kotlin/JS set option transformJs to false.

Here are all available configuration options (with their defaults):

atomicfu {
  dependenciesVersion = '0.22.0' // set to null to turn-off auto dependencies
  transformJvm = true // set to false to turn off JVM transformation
  jvmVariant = "FU" // JVM transformation variant: FU,VH, or BOTH
  transformJs = true // set to false to turn off JVM transformation
}

More features

AtomicFU provides some additional features that you can use.

Arrays of atomic values

You can declare arrays of all supported atomic value types. By default arrays are transformed into the corresponding java.util.concurrent.atomic.Atomic*Array instances.

If you configure variant = "VH" an array will be transformed to plain array using VarHandle to support atomic operations.

val a = atomicArrayOfNulls<T>(size) // similar to Array constructor

val x = a[i].value // read value
a[i].value = x // set value
a[i].compareAndSet(expect, update) // do atomic operations

Atomic delegates

You can expose the value of an atomic property to the public, using a delegated property declared in the same scope:

private val _foo = atomic<T>(initial) // private atomic, convention is to name it with leading underscore
public var foo: T by _foo            // public delegated property (val/var)

You can also delegate a property to the atomic factory invocation, that is equal to declaring a volatile property:

public var foo: T by atomic(0)

This feature is only supported for the IR transformation mode, see the atomicfu compiler plugin section for details.

User-defined extensions on atomics

You can define you own extension functions on AtomicXxx types but they must be inline and they cannot be public and be used outside of the module they are defined in. For example:

@Suppress("NOTHING_TO_INLINE")
private inline fun AtomicBoolean.tryAcquire(): Boolean = compareAndSet(false, true)

Locks

This project includes kotlinx.atomicfu.locks package providing multiplatform locking primitives that require no additional runtime dependencies on Kotlin/JVM and Kotlin/JS with a library implementation for Kotlin/Native.

  • SynchronizedObject is designed for inheritance. You write class MyClass : SynchronizedObject() and then use synchronized(instance) { ... } extension function similarly to the synchronized function from the standard library that is available for JVM. The SynchronizedObject superclass gets erased (transformed to Any) on JVM and JS, with synchronized leaving no trace in the code on JS and getting replaced with built-in monitors for locking on JVM.

  • ReentrantLock is designed for delegation. You write val lock = reentrantLock() to construct its instance and use lock/tryLock/unlock functions or lock.withLock { ... } extension function similarly to the way jucl.ReentrantLock is used on JVM. On JVM it is a typealias to the later class, erased on JS.

Note that package kotlinx.atomicfu.locks is experimental explicitly even while atomicfu is experimental itself, meaning that no ABI guarantees are provided whatsoever. API from this package is not recommended to use in libraries that other projects depend on.

Tracing operations

You can debug your tests tracing atomic operations with a special trace object:

private val trace = Trace()
private val current = atomic(0, trace)

fun update(x: Int): Int {           
    // custom trace message
    trace { "calling update($x)" }
    // automatic tracing of modification operations 
    return current.getAndAdd(x)
}

All trace messages are stored in a cyclic array inside trace.

You can optionally set the size of trace's message array and format function. For example, you can add a current thread name to the traced messages:

private val trace = Trace(size = 64) {   
    index, // index of a trace message 
    text   // text passed when invoking trace { text }
    -> "$index: [${Thread.currentThread().name}] $text" 
} 

trace is only seen before transformation and completely erased after on Kotlin/JVM and Kotlin/JS.

Kotlin Native support

Atomic references for Kotlin/Native are based on FreezableAtomicReference and every reference that is stored to the previously frozen (shared with another thread) atomic is automatically frozen, too.

Since Kotlin/Native does not generally provide binary compatibility between versions, you should use the same version of Kotlin compiler as was used to build AtomicFU. See gradle.properties in AtomicFU project for its kotlin_version.

Available Kotlin/Native targets are based on non-deprecated official targets Tier list with the corresponding compatibility guarantees.

More Repositories

1

anko

Pleasant Android application development
Kotlin
15,927
star
2

kotlinx.coroutines

Library support for Kotlin coroutines
Kotlin
12,203
star
3

kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Kotlin
5,375
star
4

dokka

API documentation engine for Kotlin
Kotlin
3,311
star
5

kotlin-examples

Various examples for Kotlin
3,177
star
6

KEEP

Kotlin Evolution and Enhancement Process
Markdown
3,109
star
7

kotlin-koans

Kotlin workshop
Kotlin
2,602
star
8

kotlinx-datetime

KotlinX multiplatform date/time library
Kotlin
2,379
star
9

kmp-production-sample

This is an open-source, mobile, cross-platform application built with Kotlin Multiplatform Mobile. It's a simple RSS reader, and you can download it from the App Store and Google Play. It's been designed to demonstrate how KMM can be used in real production projects.
Kotlin
1,984
star
10

kotlindl

High-level Deep Learning Framework written in Kotlin and inspired by Keras
Kotlin
1,467
star
11

coroutines-examples

Examples for coroutines design in Kotlin
1,465
star
12

kotlinx-kover

Kotlin
1,324
star
13

kotlin-fullstack-sample

Kotlin Full-stack Application Example
Kotlin
1,218
star
14

kotlinx.collections.immutable

Immutable persistent collections for Kotlin
Kotlin
1,153
star
15

kotlin-jupyter

Kotlin kernel for Jupyter/IPython
Kotlin
1,094
star
16

kotlinx-cli

Pure Kotlin implementation of a generic CLI parser.
Kotlin
906
star
17

kmm-basic-sample

Example of Kotlin multiplatform project
Kotlin
887
star
18

dataframe

Structured data processing in Kotlin
Kotlin
831
star
19

kotlinx-io

Kotlin multiplatform I/O library
Kotlin
817
star
20

binary-compatibility-validator

Public API management tool
Kotlin
795
star
21

kotlinx-rpc

Add asynchronous RPC services to your multiplatform applications.
Kotlin
730
star
22

kotlinconf-spinner

Kotlin
603
star
23

workshop

JetBrains Kotlin Workshop Material
Kotlin
594
star
24

kotlin-interactive-shell

Kotlin Language Interactive Shell
Java
591
star
25

kdoctor

Environment analysis tool
Kotlin
580
star
26

kandy

Kotlin plotting library.
Kotlin
579
star
27

kotlin-frontend-plugin

Gradle Kotlin (http://kotlinlang.org) plugin for frontend development
Kotlin
570
star
28

dukat

Converter of <any kind of declarations> to Kotlin external declarations
Kotlin
552
star
29

multik

Kotlin
550
star
30

kotlin-wasm-examples

Examples with Kotlin/Wasm
519
star
31

kotlinx-benchmark

Kotlin multiplatform benchmarking toolkit
Kotlin
504
star
32

kotlin-spark-api

This projects gives Kotlin bindings and several extensions for Apache Spark. We are looking to have this as a part of Apache Spark 3.x
Kotlin
459
star
33

kotlin-by-example

The sources of Kotlin by Example.
396
star
34

kotlin-spec

Kotlin Language Specification:
Kotlin
358
star
35

kotlin-in-action

Code samples from the "Kotlin in Action" book
Kotlin
343
star
36

ts2kt

ts2kt is officially deprecated, please use https://github.com/Kotlin/dukat instead. // Converter of TypeScript definition files to Kotlin external declarations
Kotlin
320
star
37

kotlin-numpy

Kotlin bindings for NumPy
Kotlin
312
star
38

kotlin-style-guide

Work-in-progress notes for the Kotlin style guide
289
star
39

kotlinx-knit

Kotlin source code documentation management tool
Kotlin
287
star
40

anko-example

A small application built with Anko DSL
Kotlin
285
star
41

full-stack-web-jetbrains-night-sample

Full-stack demo application written with Kotlin MPP
Kotlin
271
star
42

KMP-App-Template

Kotlin Multiplatform app template with shared UI
Kotlin
269
star
43

kotlin-script-examples

Examples of Kotlin Scripts and usages of the Kotlin Scripting API
Kotlin
262
star
44

kotlinx-nodejs

Kotlin external declarations for using the Node.js API from Kotlin code targeting JavaScript
Kotlin
212
star
45

kotlin-eclipse

Kotlin Plugin for Eclipse
Kotlin
186
star
46

Storytale

Kotlin
165
star
47

kotlinx.reflect.lite

Lightweight library allowing to introspect basic stuff about Kotlin symbols
Kotlin
150
star
48

api-guidelines

Best practices to consider when writing an API for your library
144
star
49

kotlin-benchmarks

This is the project to verify and investigate performance issues in Kotlin and standard library.
Kotlin
136
star
50

kotlin-libs-publisher

Gradle plugin for publishing of Kotlin libs
Kotlin
119
star
51

kotlinx-browser

Kotlin browser API
Kotlin
110
star
52

kotlindl-app-sample

This repo demonstrates how to use KotlinDL for neural network inference on Android devices.
Kotlin
96
star
53

kotlin-koans-edu

Kotlin Koans for Educational Plugin and play.kotl.in
Kotlin
93
star
54

KMP-App-Template-Native

Kotlin Multiplatform app template with native UI
Kotlin
85
star
55

grammar-tools

Tokenization and parsing Kotlin code using the ANTLR Kotlin grammar
Kotlin
83
star
56

kmm-integration-sample

Kotlin
76
star
57

kmm-with-cocoapods-sample

This project represents the case when Cocoapods dependencies are added in Kotlin and there is no existing Xcode project
Kotlin
57
star
58

kotlin-koans-edu-obsolete

Obsolete: check https://github.com/Kotlin/kotlin-koans-edu for the latest version.
Kotlin
55
star
59

kotlin-native-calculator-sample

55
star
60

kotlinx.support

Extension and top-level functions to use JDK7/JDK8 features in Kotlin 1.0
Kotlin
54
star
61

js-externals

External declarations for Kotlin/JS
53
star
62

k2-performance-metrics

Measure Kotlin K2 compiler performance in your repository
Jupyter Notebook
45
star
63

kmp-native-wizard

A mostly-empty template to get started creating a Kotlin/Native project.
Kotlin
43
star
64

coroutines-workshop

Materials for a full-day workshop on Kotlin Coroutines
Kotlin
42
star
65

swift-export-sample

Kotlin to Swift technology preview
Swift
39
star
66

kotlin-playground-wp-plugin

WordPress plugin which allows to embed interactive Kotlin playground to any post via [kotlin] shortcode
PHP
35
star
67

io2019-serverside-demo

E2E Sample
Kotlin
31
star
68

kotlin-jupyter-libraries

Library descriptors for Kotlin kernel for Jupyter
29
star
69

kmm-with-cocoapods-multitarget-xcode-sample

This project is intended to demonstrate how to connect Kotlin library to Xcode project with several targets: iOS, macOS, tvOS, watchOS
Swift
23
star
70

xcode-compat

AppCode helper for Kotlin/Native and Xcode
Kotlin
21
star
71

kotlin-in-action-2e

Code samples for the second edition of "Kotlin in Action".
Kotlin
20
star
72

kotlin-wasm-compose-template

A template repository for Compose Multiplatform with Kotlin/Wasm target
Kotlin
20
star
73

kotlinx.dom

Kotlin
17
star
74

kotlin-wasm-benchmarks

Kotlin Multiplatform Collection of Benchmarks focused on Kotlin/Wasm performance
Kotlin
13
star
75

dokka-plugin-template

Dokka plugin quickstart template with pre-configured dependencies and publishing
Kotlin
12
star
76

kotlinx.team.infra

Kotlin
10
star
77

multiplatform-library-template

Kotlin
10
star
78

kotlin-js-inspection-pack-plugin

Adds useful inspections, intentions, and quick-fixes for working with Kotlin/JS projects.
Kotlin
10
star
79

obsolete-kotlin-swing

Experimental library providing some helper functions and extensions for creating Swing user interfaces.
Kotlin
8
star
80

kotlin-in-action-2e-jkid

Sample project accompanying the second edition of "Kotlin in Action". JSON serialization/deserialization library for Kotlin data classes
Kotlin
8
star
81

kotlin-wasm-browser-template

A template repository for Kotlin/Wasm on browser
HTML
8
star
82

kotlin-spark-shell

Kotlin Language support for Apache Spark
Kotlin
7
star
83

obsolete-kotlin-jdbc

Experimental library providing some helper functions and extensions for working with JDBC in Kotlin.
Kotlin
7
star
84

community-project-gradle-plugin

Kotlin
6
star
85

website-grammar-generator

Kotlin ANTLR grammar converter to XML for the Kotlin website or text file
Kotlin
6
star
86

kotlin-grammar-gpl2

Kotlin grammar ANTLR sources (under GPLv2)
ANTLR
6
star
87

web-site-samples

Examples repository for kotlinlang.org
4
star
88

kotlin-build-report-sample

Kotlin
4
star
89

kotlin-wasm-wasi-template

A template repository for Kotlin/Wasm with WASI
Kotlin
4
star
90

kotlin-jupyter-http-util

Ktor client and serialization for Kotlin Jupyter Notebooks
Kotlin
3
star
91

kotlin-cocoapods-spec

Ruby
3
star
92

analysis-api

Kotlin Analysis API Documentation
3
star
93

kotlin.github.io

Redirect to kotlinlang.org and favicon/title provider for kotlin.github.io/* websites.
HTML
2
star
94

kotlin-wasm-nodejs-template

A template repository for Kotlin/Wasm on Node.js
Kotlin
1
star
95

kmm-with-cocoapods-xcode-two-kotlin-libraries-sample

This project is intended to demonstrate the connection of two Kotlin libraries to existing Xcode project through Cocoapods
Kotlin
1
star