- Annotation
- Extension Properties
- annotationClass
- Inheritors
- AssociatedObjectKey
- BetaInteropApi
- BuilderInference
- CCall
- CEnumEntryAlias
- CEnumVarTypeSize
- CName
- ContextFunctionTypeParams
- CStruct
- Deprecated
- DeprecatedSinceKotlin
- DslMarker
- EagerInitialization
- EagerInitialization
- ExperimentalAssociatedObjects
- ExperimentalContracts
- ExperimentalEncodingApi
- Volatile
- Volatile
- Shared mutable state and concurrency
- The problem
- Volatiles are of no help
- Thread-safe data structures
- Thread confinement fine-grained
- Thread confinement coarse-grained
- Mutual exclusion
- Kotlin volatile что это
- AtomicNativePtr
- AtomicReference
- Annotations
- Volatile
- Extensions for External Classes
- java.lang.ThreadLocal
- java.util.concurrent.locks.Lock
- java.util.concurrent.locks.ReentrantReadWriteLock
- java.util.Timer
- Functions
- fixedRateTimer
Annotation
Base interface implicitly implemented by all annotation interfaces. See Kotlin language documentation for more information on annotations.
Extension Properties
annotationClass
Returns a KClass instance corresponding to the annotation type of this annotation.
Inheritors
AssociatedObjectKey
Makes the annotated annotation class an associated object key.
BetaInteropApi
Marks Objective-C and Swift interoperability API as Beta.
BuilderInference
Allows to infer generic type arguments of a function from the calls in the annotated function parameter of that function.
CCall
CEnumEntryAlias
Denotes property that is an alias to some enum entry.
CEnumVarTypeSize
Stores instance size of the type T: CEnumVar.
CName
Makes top level function available from C/C++ code with the given name.
ContextFunctionTypeParams
Signifies that the annotated functional type has the prefix of size count for context receivers. Thus, @ContextFunctionTypeParams(2) @ExtensionFunctionType Function4 is a normalized representation of context(String, Int) Double.(Byte) -> Unit .
CStruct
Deprecated
Marks the annotated declaration as deprecated.
DeprecatedSinceKotlin
Marks the annotated declaration as deprecated. In contrast to Deprecated, severity of the reported diagnostic is not a constant value, but differs depending on the API version of the usage (the value of the -api-version argument when compiling the module where the usage is located). If the API version is greater or equal than hiddenSince, the declaration will not be accessible from the code (as if it was deprecated with level DeprecationLevel.HIDDEN), otherwise if the API version is greater or equal than errorSince, the usage will be marked as an error (as with DeprecationLevel.ERROR), otherwise if the API version is greater or equal than warningSince, the usage will be marked as a warning (as with DeprecationLevel.WARNING), otherwise the annotation is ignored.
DslMarker
When applied to annotation class X specifies that X defines a DSL language
EagerInitialization
Forces a top-level property to be initialized eagerly, opposed to lazily on the first access to file and/or property.
EagerInitialization
Forces a top-level property to be initialized eagerly, opposed to lazily on the first access to file and/or property. This annotation can be used as temporal migration assistance during the transition from the previous Kotlin/Native initialization scheme «eager by default» to the new one, «lazy by default».
ExperimentalAssociatedObjects
The experimental marker for associated objects API.
ExperimentalContracts
This marker distinguishes the experimental contract declaration API and is used to opt-in for that feature when declaring contracts of user functions.
ExperimentalEncodingApi
This annotation marks the experimental API for encoding and decoding between binary data and printable ASCII character sequences.
Volatile
Marks the JVM backing field of the annotated var property as volatile , meaning that reads and writes to this field are atomic and writes are always made visible to other threads. If another thread reads the value of this field (e.g. through its accessor), it sees not only that value, but all side effects that led to writing that value.
Note that only backing field operations are atomic when the field is annotated with Volatile . For example, if the property getter or setter make several operations with the backing field, a property operation, i.e. reading or setting it through these accessors, is not guaranteed to be atomic.
For Common
Marks the JVM backing field of the annotated var property as volatile , meaning that reads and writes to this field are atomic and writes are always made visible to other threads. If another thread reads the value of this field (e.g. through its accessor), it sees not only that value, but all side effects that led to writing that value.
This annotation has effect only in Kotlin/JVM. It’s recommended to use kotlin.concurrent.Volatile annotation instead in multiplatform projects.
Note that only backing field operations are atomic when the field is annotated with Volatile . For example, if the property getter or setter make several operations with the backing field, a property operation, i.e. reading or setting it through these accessors, is not guaranteed to be atomic.
Volatile
Marks the JVM backing field of the annotated var property as volatile , meaning that reads and writes to this field are atomic and writes are always made visible to other threads. If another thread reads the value of this field (e.g. through its accessor), it sees not only that value, but all side effects that led to writing that value.
Note that only backing field operations are atomic when the field is annotated with Volatile . For example, if the property getter or setter make several operations with the backing field, a property operation, i.e. reading or setting it through these accessors, is not guaranteed to be atomic.
For Common
Marks the backing field of the annotated var property as volatile , meaning that reads and writes to this field are atomic and writes are always made visible to other threads. If another thread reads the value of this field (e.g. through its accessor), it sees not only that value, but all side effects that led to writing that value.
This annotation has effect in Kotlin/JVM and Kotlin/Native.
Note that only backing field operations are atomic when the field is annotated with Volatile . For example, if the property getter or setter make several operations with the backing field, a property operation, i.e. reading or setting it through these accessors, is not guaranteed to be atomic.
For Native
Marks the backing field of the annotated var property as volatile , meaning that reads and writes to this field are atomic and writes are always made visible to other threads. If another thread reads the value of this field (e.g. through its accessor), it sees not only that value, but all side effects that led to writing that value.
Note that only backing field operations are atomic when the field is annotated with Volatile . For example, if the property getter or setter make several operations with the backing field, a property operation, i.e. reading or setting it through these accessors, is not guaranteed to be atomic.
Shared mutable state and concurrency
Coroutines can be executed parallelly using a multi-threaded dispatcher like the Dispatchers.Default. It presents all the usual parallelism problems. The main problem being synchronization of access to shared mutable state. Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, but others are unique.
The problem
Let us launch a hundred coroutines all doing the same action a thousand times. We’ll also measure their completion time for further comparisons:
We start with a very simple action that increments a shared mutable variable using multi-threaded Dispatchers.Default.
You can get the full code here.
What does it print at the end? It is highly unlikely to ever print «Counter = 100000», because a hundred coroutines increment the counter concurrently from multiple threads without any synchronization.
Volatiles are of no help
There is a common misconception that making a variable volatile solves concurrency problem. Let us try it:
import kotlinx.coroutines.* import kotlin.system.* suspend fun massiveRun(action: suspend () -> Unit) < val n = 100 // number of coroutines to launch val k = 1000 // times an action is repeated by each coroutine val time = measureTimeMillis < coroutineScope < // scope for coroutines repeat(n) < launch < repeat(k) < action() >> > > > println(«Completed $
You can get the full code here.
This code works slower, but we still don’t always get «Counter = 100000» at the end, because volatile variables guarantee linearizable (this is a technical term for «atomic») reads and writes to the corresponding variable, but do not provide atomicity of larger actions (increment in our case).
Thread-safe data structures
The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, linearizable, or atomic) data structure that provides all the necessary synchronization for the corresponding operations that needs to be performed on a shared state. In the case of a simple counter we can use AtomicInteger class which has atomic incrementAndGet operations:
You can get the full code here.
This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other standard data structures and basic operations on them. However, it does not easily scale to complex state or to complex operations that do not have ready-to-use thread-safe implementations.
Thread confinement fine-grained
Thread confinement is an approach to the problem of shared mutable state where all access to the particular shared state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to the single event-dispatch/application thread. It is easy to apply with coroutines by using a single-threaded context.
You can get the full code here.
This code works very slowly, because it does fine-grained thread-confinement. Each individual increment switches from multi-threaded Dispatchers.Default context to the single-threaded context using withContext(counterContext) block.
Thread confinement coarse-grained
In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic are confined to the single thread. The following example does it like that, running each coroutine in the single-threaded context to start with.
You can get the full code here.
This now works much faster and produces correct result.
Mutual exclusion
Mutual exclusion solution to the problem is to protect all modifications of the shared state with a critical section that is never executed concurrently. In a blocking world you’d typically use synchronized or ReentrantLock for that. Coroutine’s alternative is called Mutex. It has lock and unlock functions to delimit a critical section. The key difference is that Mutex.lock() is a suspending function. It does not block a thread.
There is also withLock extension function that conveniently represents mutex.lock(); try < . >finally < mutex.unlock() >pattern:
You can get the full code here.
The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations where you absolutely must modify some shared state periodically, but there is no natural thread that this state is confined to.
Kotlin volatile что это
A Long value that is always updated atomically. For additional details about atomicity guarantees for reads and writes see kotlin.concurrent.Volatile.
AtomicNativePtr
A kotlinx.cinterop.NativePtr value that is always updated atomically. For additional details about atomicity guarantees for reads and writes see kotlin.concurrent.Volatile.
AtomicReference
An object reference that is always updated atomically.
Annotations
Volatile
Marks the backing field of the annotated var property as volatile , meaning that reads and writes to this field are atomic and writes are always made visible to other threads. If another thread reads the value of this field (e.g. through its accessor), it sees not only that value, but all side effects that led to writing that value.
Extensions for External Classes
java.lang.ThreadLocal
java.util.concurrent.locks.Lock
java.util.concurrent.locks.ReentrantReadWriteLock
java.util.Timer
Functions
fixedRateTimer
Creates a timer that executes the specified action periodically, starting after the specified initialDelay (expressed in milliseconds) and with the interval of period milliseconds between the start of the previous task and the start of the next one.
fun fixedRateTimer (
name : String ? = null ,
daemon : Boolean = false ,
initialDelay : Long = 0.toLong() ,
period : Long ,
action : TimerTask . ( ) -> Unit
) : Timer
Creates a timer that executes the specified action periodically, starting at the specified startAt date and with the interval of period milliseconds between the start of the previous task and the start of the next one.
fun fixedRateTimer (
name : String ? = null ,
daemon : Boolean = false ,
startAt : Date ,
period : Long ,
action : TimerTask . ( ) -> Unit
) : Timer