4nt*_*ine 3 multithreading let thread-synchronization kotlin
Kotlin ?.let线程安全吗?
假设a变量可以在不同的线程中更改。使用a?.let { /* */ }线程安全吗?如果等于,那么是否if (a != null) { block() }可能其中if不为null且block其中已经为null?
a?.let { block() } is indeed equivalent to if (a != null) block().
This also means that if a is a mutable variable, then:
a might be reassigned after the null check and hold a null value when block() is executed;
All concurrency-related effects are in power, and proper synchronization is required if a is shared between threads to avoid a race condition;
但是,由于let { ... }实际上take 作为其接受函数的单个参数传递了它的接收者,因此它可以用于捕获alambda 的值并在lambda中使用它,而不是再次访问block()。例如:
a?.let { notNullA -> block(notNullA) }
// with implicit parameter `it`, this is equivalent to:
a?.let { block(it) }
Run Code Online (Sandbox Code Playgroud)
在此,a保证将传递为lambda的参数的值与检查为null的值相同。但是,a再次观察block()可能返回null或不同的值,并且观察给定实例的可变状态也应正确同步。
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |