Kotlin`..let`是线程安全的吗? [英] Is Kotlin `?.let` thread-safe?

查看:161
本文介绍了Kotlin`..let`是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

  1. a可能在执行空检查之后重新分配,并在执行block()时保持null值;

  1. a might be reassigned after the null check and hold a null value when block() 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`是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆