commit | 3711220c0ebc49aadcbb4384c6a568703352f82b | [log] [tgz] |
---|---|---|
author | Haibo Huang <hhb@google.com> | Wed Jul 15 03:57:40 2020 +0000 |
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | Wed Jul 15 03:57:40 2020 +0000 |
tree | 950a5189966a833d7bfd1da98ffd75cf6b1ce5c0 | |
parent | 9249de9dd3e01cd67415c2b72eeeedaaa2bda0d1 [diff] | |
parent | 9b999a31d9a334b6a97012d8f1bd3a8f3c5f5ddc [diff] |
Upgrade kotlinx.atomicfu to 0.14.3 am: fe5a26f975 am: d6bdd137d9 am: 122ccb7269 am: 9b999a31d9 Original change: https://android-review.googlesource.com/c/platform/external/kotlinx.atomicfu/+/1360988 Change-Id: I382375e3746b6c760dfc76253f598c25736c85cb
The idiomatic way to use atomic operations in Kotlin.
AtomicReference/Int/Long
, but run it in production efficiently as AtomicXxxFieldUpdater
on Kotlin/JVM and as plain unboxed values on Kotlin/JS.updateAndGet
and getAndUpdate
functions).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.
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.top.compareAndSet(...)
is Ok, while val tmp = top; tmp...
is not.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.private val _foo = atomic<T>(initial) // private atomic, convention is to name it with leading underscore public var foo: T // public val/var get() = _foo.value set(value) { _foo.value = value }
Building with Gradle is supported for all platforms.
You will need Gradle 4.10 or later. Add and apply AtomicFU plugin. It adds all the corresponding dependencies and transformations automatically. See additional configuration if that needs tweaking.
buildscript { ext.atomicfu_version = '0.14.3' dependencies { classpath "org.jetbrains.kotlinx:atomicfu-gradle-plugin:$atomicfu_version" } } apply plugin: 'kotlinx-atomicfu'
Configure add apply plugin just like for JVM.
This library is available for Kotlin/Native (atomicfu-native
). Kotlin/Native uses Gradle metadata and needs Gradle version 5.3 or later. See Gradle Metadata 1.0 announcement for more details. Apply the corresponding plugin just like for JVM.
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
.
If you write a common code that should get compiled or different platforms, add org.jetbrains.kotlinx:atomicfu-common
to your common code dependencies or apply kotlinx-atomicfu
plugin that adds this dependency automatically:
dependencies { compile "org.jetbrains.kotlinx:atomicfu-common:$atomicfu_version" }
There are the following additional parameters (with their defaults):
atomicfu { dependenciesVersion = '0.14.3' // set to null to turn-off auto dependencies transformJvm = true // set to false to turn off JVM transformation transformJs = true // set to false to turn off JS transformation variant = "FU" // JVM transformation variant: FU,VH, or BOTH verbose = false // set to true to be more verbose }
Declare AtomicFU version:
<properties> <atomicfu.version>0.14.3</atomicfu.version> </properties>
Declare provided dependency on the AtomicFU library (the users of the resulting artifact will not have a dependency on 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> <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> <!-- "VH" to use Java 9 VarHandle, "BOTH" to produce multi-version code --> <variant>FU</variant> </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> </configuration> </execution> </executions> </plugin> </plugins> </build>
AtomicFU provides some additional features that you can optionally use.
AtomicFU can produce code that uses Java 9 VarHandle instead of AtomicXxxFieldUpdater
. Configure transformation variant
in Gradle build file:
atomicfu { variant = "VH" }
It can also create JEP 238 multi-release jar file with both AtomicXxxFieldUpdater
for JDK<=8 and VarHandle
for for JDK9+ if you set variant
to "BOTH"
.
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
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)
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.
Condition variables (notify
/wait
and signal
/await
) are not supported.
You can optionally test lock-freedomness of lock-free data structures using LockFreedomTestEnvironment
class. See example in LockFreeQueueLFTest
. Testing is performed by pausing one (random) thread before or after a random state-update operation and making sure that all other threads can still make progress.
In order to make those test to actually perform lock-freedomness testing you need to configure an additional execution of tests with the original (non-transformed) classes for Maven:
<build> <plugins> <!-- additional test execution with surefire on non-transformed files --> <plugin> <artifactId>maven-surefire-plugin</artifactId> <executions> <execution> <id>lockfree-test</id> <phase>test</phase> <goals> <goal>test</goal> </goals> <configuration> <classesDirectory>${project.build.directory}/classes-pre-atomicfu</classesDirectory> <includes> <include>**/*LFTest.*</include> </includes> </configuration> </execution> </executions> </plugin> </plugins> </build>
For Gradle there is nothing else to add. Tests are always run using original (non-transformed) classes.