问题描述
Kotlin ?.let
是线程安全的吗?
Is Kotlin ?.let
thread-safe?
比方说a
变量可以在不同的线程中更改.使用a?.let { /* */ }
线程安全吗?如果它等于if (a != null) { block() }
,是否可能发生if
中不为空且在block
中已经为空的情况?
Let's say a
variable can be changed in different thread.Is using a?.let { /* */ }
thread-safe? If it's equal to if (a != null) { block() }
can it happen that in if
it's not null and in block
it's already null?
推荐答案
a?.let { block() }
确实等同于if (a != null) block()
.
这还意味着,如果a
是可变变量,则:
This also means that if a
is a mutable variable, then:
-
a
可能在执行空检查之后重新分配,并在执行block()
时保持null
值;
a
might be reassigned after the null check and hold anull
value whenblock()
is executed;
所有与并发相关的作用都有效,并且如果在线程之间共享a
以避免出现竞争状况,则需要正确的同步;
All concurrency-related effects are in power, and proper synchronization is required if a
is shared between threads to avoid a race condition;
但是,由于let { ... }
实际上将其接收者作为接收函数的单个参数传递给它,因此它可以用于捕获a
的值并在lambda中使用它,而不用再次访问block()
.例如:
However, as let { ... }
actually passes its receiver as the single argument to the function it takes, it can be used to capture the value of a
and use it inside the lambda instead of accessing the property again in the block()
. For example:
a?.let { notNullA -> block(notNullA) }
// with implicit parameter `it`, this is equivalent to:
a?.let { block(it) }
在此,保证将作为参数传递给lambda的a
的值与检查为null的值相同.但是,再次在block()
中观察a
可能会返回null或其他值,并且观察给定实例的可变状态也应该正确同步.
Here, the value of a
passed as the argument into the lambda is guaranteed to be the same value that was checked for null. However, observing a
again in the block()
might return a null or a different value, and observing the mutable state of the given instance should also be properly synchronized.
这篇关于Kotlin`..let`是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!