- Notifications
You must be signed in to change notification settings - Fork71
The idiomatic way to use atomic operations in Kotlin
License
Kotlin/kotlinx-atomicfu
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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 providestrict compatibility guarantees on plugin API and its general stability between Kotlin versions.
Atomicfu is a multiplatform library that provides the idiomatic and efficient way of using atomic operations in Kotlin.
- Requirements
- Features
- Example
- Quickstart
- Usage constraints
- Transformation modes
- Options for post-compilation transformation
- More features
- Kotlin/Native support
To apply the current version of the atomicfu Gradle plugin, your project has to use:
Gradle
8.2or newerKotlin
2.2.0or newer
Consider usingprevious versions of the pluginif your project could not meet these requirements.
Note on Kotlin version: Currently, the
kotlinx-atomicfuGradle plugin only relies on the version of Kotlin Gradle Plugin (KGP) present in the user's project.It's important to note this constraint if your project configures the custom Kotlin compiler version or modifies the Kotlin Native compiler version usingkotlin.native.versionproperty.
- Complete multiplatform support: JVM, Native, JS and Wasm (since Kotlin 1.9.20).
- Code it like a boxed value
atomic(0), but run it in production efficiently:- ForJVM: an atomic value is represented as a plain value atomically updated with
java.util.concurrent.atomic.AtomicXxxFieldUpdaterfrom the Java standard library. - ForJS: an atomic value is represented as a plain value.
- ForNative: atomic operations are delegated to Kotlin/Native atomic intrinsics.
- ForWasm: an atomic value is not transformed, it remains boxed, and
kotlinx-atomicfulibrary is used as a runtime dependency.
- ForJVM: an atomic value is represented as a plain value atomically updated with
- Use Kotlin-specific extensions (e.g. inline
loop,update,updateAndGetfunctions). - Use atomic arrays, user-defined extensions on atomics and locks (seemore features).
- Tracing operations for debugging.
Let us declare atop variable for a lock-free stack implementation:
importkotlinx.atomicfu.*// import top-level functions from kotlinx.atomicfuprivateval top= atomic<Node?>(null)
Usetop.value to perform volatile reads and writes:
funisEmpty()= top.value==null// volatile readfunclear() { top.value=null }// volatile write
UsecompareAndSet 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-levelupdate,updateAndGet, andgetAndUpdate,when possible, for idiomatic lock-free code, for example:
funpush(v:Value)= top.update { cur->Node(v, cur) }funpop():Value?= top.getAndUpdate { cur-> cur?.next } ?.value
Declare atomic integers and longs using type inference:
val myInt= atomic(0)// note: integer initial valueval myLong= atomic(0L)// note: long initial value
Integer and long atomics provide all the usualgetAndIncrement,incrementAndGet,getAndAdd,addAndGet, and etcoperations. They can be also atomically modified via+= and-= operators.
New plugin id: Please pay attention, that starting from version
0.25.0the plugin id isorg.jetbrains.kotlinx.atomicfu
Add the following to your top-level build file:
Kotlin
plugins { id("org.jetbrains.kotlinx.atomicfu") version"0.30.0-beta"}Groovy
plugins { id'org.jetbrains.kotlinx.atomicfu' version'0.30.0-beta'}Kotlin
buildscript { repositories { mavenCentral() } dependencies { classpath("org.jetbrains.kotlinx:atomicfu-gradle-plugin:0.30.0-beta") }}apply(plugin="org.jetbrains.kotlinx.atomicfu")Groovy
buildscript { repositories { mavenCentral() } dependencies { classpath'org.jetbrains.kotlinx:atomicfu-gradle-plugin:0.30.0-beta' }} applyplugin:'org.jetbrains.kotlinx.atomicfu'Maven configuration is supported for JVM projects.
Declare atomicfu version
<properties> <atomicfu.version>0.30.0-beta</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 differentclasses-pre-atomicfu directory,which is then transformed to a regularclasses 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>
- Declare atomic variables as
private valorinternal 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(seeatomic delegates section for details):
privateval_foo= atomic<T>(initial)// private atomic, convention is to name it with leading underscorepublicvar foo:T by_foo// public delegated property (val/var)
- Only simple operations on atomic variablesdirectly are supported.
- Do not read references on atomic variables into local variables,e.g.
top.compareAndSet(...)is ok, whileval tmp = top; tmp...is not. - Do not leak references on atomic variables in other way (return, pass as params, etc).
- Do not read references on atomic variables into local variables,e.g.
- Do not introduce complex data flow in parameters to atomic variable operations,i.e.
top.value = complex_expressionandtop.compareAndSet(cur, complex_expression)are not supported(more specifically,complex_expressionshould not have branches in its compiled representation).Extractcomplex_expressioninto a variable when needed.
To provide a user-friendly atomic API on the frontend and efficient usage of atomic values on the backend kotlinx-atomicfu library uses the compiler plugin to transformIR for all the target backends:
- JVM: atomics are replaced with
java.util.concurrent.atomic.AtomicXxxFieldUpdater. - Native: atomics are implemented via atomic intrinsics on Kotlin/Native.
- JS: atomics are unboxed and represented as plain values.
To turn on IR transformations set the following properties in yourgradle.properties file:
Please note, that starting from version
0.24.0of the library your project is required to useKotlin version >= 1.9.0.See therequirements section.
kotlinx.atomicfu.enableJvmIrTransformation=true// for JVM IR transformationkotlinx.atomicfu.enableNativeIrTransformation=true// for Native IR transformationkotlinx.atomicfu.enableJsIrTransformation=true// for JS IR transformation
Here are the configuration properties in case you use older versions of the library lower than 0.24.0.
ForKotlin >= 1.7.20
kotlinx.atomicfu.enableJvmIrTransformation=true// for JVM IR transformationkotlinx.atomicfu.enableNativeIrTransformation=true// for Native IR transformationkotlinx.atomicfu.enableJsIrTransformation=true// for JS IR transformation
ForKotlin >= 1.6.20 andKotlin < 1.7.20
kotlinx.atomicfu.enableIrTransformation=true// only JS IR transformation is supported
Also for JS backend make sure thatir orboth compiler mode is set:
kotlin.js.compiler=ir// or both
Some configuration options are available forpost-compilation transform tasks on JVM and JS.
To set configuration options you should createatomicfu section in abuild.gradle file,like this:
atomicfu { dependenciesVersion='0.30.0-beta'}To turn off transformation for Kotlin/JVM set optiontransformJvm tofalse.
Configuration optionjvmVariant defines the Java class that replaces atomics during bytecode transformation.Here are the valid options:
FU– atomics are replaced withAtomicXxxFieldUpdater.VH– atomics are replaced withVarHandle,this option is supported for JDK 9+.BOTH–multi-release jar file will be created with bothAtomicXxxFieldUpdaterfor JDK <= 8 andVarHandlefor JDK 9+.
Starting from version
0.26.0transformJsflag does not take any effect and is disabled by default.Please ensure that this flag is not used in the atomicfu configuration of your project, you can safely remove it.
Here are all available configuration options (with their defaults):
atomicfu { dependenciesVersion='0.30.0-beta'// 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}AtomicFU provides some additional features that you can use.
You can declare arrays of all supported atomic value types.By default arrays are transformed into the correspondingjava.util.concurrent.atomic.Atomic*Array instances.
If you configurevariant = "VH" an array will be transformed to plain array usingVarHandle to support atomic operations.
val a= atomicArrayOfNulls<T>(size)// similar to Array constructorval x= a[i].value// read valuea[i].value= x// set valuea[i].compareAndSet(expect, update)// do atomic operations
You can expose the value of an atomic property to the public, using a delegated propertydeclared in the same scope:
privateval_foo= atomic<T>(initial)// private atomic, convention is to name it with leading underscorepublicvar 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:
publicvar foo:T by atomic(0)
This feature is only supported for the IR transformation mode, see theatomicfu compiler plugin section for details.
You can define you own extension functions onAtomicXxx types but they must beinline and they cannotbe public and be used outside of the module they are defined in. For example:
@Suppress("NOTHING_TO_INLINE")privateinlinefun AtomicBoolean.tryAcquire():Boolean= compareAndSet(false,true)
This project includeskotlinx.atomicfu.locks package providing multiplatform locking primitives thatrequire no additional runtime dependencies on Kotlin/JVM and Kotlin/JS with a library implementation forKotlin/Native.
SynchronizedObjectis designed for inheritance. You writeclass MyClass : SynchronizedObject()and thenusesynchronized(instance) { ... }extension function similarly to thesynchronizedfunction from the standard library that is available for JVM. TheSynchronizedObjectsuperclass gets erased(transformed toAny) on JVM and JS, withsynchronizedleaving no trace in the code on JS and gettingreplaced with built-in monitors for locking on JVM.ReentrantLockis designed for delegation. You writeval lock = reentrantLock()to construct its instance anduselock/tryLock/unlockfunctions orlock.withLock { ... }extension function similarly to the wayjucl.ReentrantLockis used on JVM. On JVM it is a typealias to the later class, erased on JS.
Note that package
kotlinx.atomicfu.locksis 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 librariesthat other projects depend on.
You can debug your tests tracing atomic operations with a special trace object:
privateval trace=Trace()privateval current= atomic(0, trace)funupdate(x:Int):Int {// custom trace message trace {"calling update($x)" }// automatic tracing of modification operationsreturn current.getAndAdd(x)}
All trace messages are stored in a cyclic array insidetrace.
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:
privateval 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.
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.Seegradle.properties in AtomicFU project for itskotlin_version.
Available Kotlin/Native targets are based on non-deprecated official targetsTier listwith the corresponding compatibility guarantees.
Gradle Build Scans can provide insights into an Atomicfu Build.JetBrains runs aGradle Develocity server.that can be used to automatically upload reports.
To automatically opt in add the following to$GRADLE_USER_HOME/gradle.properties.
org.jetbrains.atomicfu.build.scan.enabled=true# optionally provide a username that will be attached to each reportorg.jetbrains.atomicfu.build.scan.username=John Wick
A Build Scan may contain identifiable information. See the Terms of Usehttps://gradle.com/legal/terms-of-use/.
About
The idiomatic way to use atomic operations in Kotlin
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.