Kotlin`..let`是线程安全的吗?

4nt*_*ine 3 multithreading let thread-synchronization kotlin

Kotlin ?.let线程安全吗?

假设a变量可以在不同的线程中更改。使用a?.let { /* */ }线程安全吗?如果等于,那么是否if (a != null) { block() }可能其中if不为null且block其中已经为null?

hot*_*key 5

a?.let { block() } is indeed equivalent to if (a != null) block().

This also means that if a is a mutable variable, then:

  1. a might be reassigned after the null check and hold a null value when block() is executed;

  2. 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或不同的值,并且观察给定实例的可变状态也应正确同步。

  • …后一种情况是线程安全的。(从某种意义上说,“let”参数始终与“?.”检查的值相同,因此永远不能为空。但是,如果“a”同时发生变化,则不会反映出来.) (3认同)