A store of a final field (inside a constructor) and, if the field is a reference, any store that this final can reference, cannot be reordered with a subsequent store (outside that constructor) of the reference to the object holding that field into a variable accessible to other threads. For example, you cannot reorder
时间: 2024-02-23 16:02:21 浏览: 23
写入 final 字段的操作(在构造函数内部),以及如果该字段是一个引用类型,则任何该 final 引用可以引用的对象的写入操作,都不能与将持有该字段的对象的引用存储到其他线程可访问的变量中(在构造函数外部)的操作进行重排序。
例如,您不能将以下代码进行重排序:
```java
class Example {
final int x;
Object y;
public Example() {
x = 1;
y = new Object();
}
public void publish() {
ExampleHolder.INSTANCE.set(this);
}
}
class ExampleHolder {
static Example INSTANCE;
static void set(Example e) {
INSTANCE = e;
}
}
```
在这个例子中,如果将 `INSTANCE` 的写入操作重排序到 `x` 和 `y` 的写入操作之前,那么在 `publish()` 方法被调用之前,其他线程可能会看到 `INSTANCE` 引用的对象的 `x` 和 `y` 字段为默认值,而不是构造函数中设置的值。这可能会导致程序出现不一致的行为。因此,Java 内存模型禁止这种重排序行为。
相关问题
e is a constructor and should be called with the `new` keyword
这个提示意味着你正在尝试调用一个构造函数,但没有使用 `new` 关键字来创建一个新的对象实例。在 JavaScript 中,构造函数必须使用 `new` 关键字来创建一个新的对象实例,否则会出现这个错误。
例如,如果你有一个构造函数 `Person`:
```
function Person(name) {
this.name = name;
}
```
你应该使用 `new` 关键字来创建一个新的 `Person` 对象实例:
```
var person1 = new Person('Alice');
```
如果你没有使用 `new` 关键字,例如这样:
```
var person2 = Person('Bob');
```
那么就会出现 `TypeError: Person is a constructor and should be called with the new keyword` 错误。
Move thr contents of this initializer to a standard constructor or to field initializers
这个提示是在告诉你将这个初始化器的内容移动到一个标准的构造函数或者字段初始化器中。
初始化器是在创建类的新实例时执行的代码块。如果你的类中存在初始化器,它们会在构造函数之前执行。然而,将初始化器中的代码移到构造函数或者字段初始化器中可能更加清晰和易于理解。
例如,如果你的代码如下所示:
```csharp
public class MyClass
{
private int _myField;
public MyClass()
{
_myField = 0;
}
{
_myField = 1;
}
}
```
你可以将初始化器中的代码移动到构造函数中,使代码更加清晰:
```csharp
public class MyClass
{
private int _myField;
public MyClass()
{
_myField = 1;
}
}
```
或者你也可以使用字段初始化器:
```csharp
public class MyClass
{
private int _myField = 1;
public MyClass()
{
}
}
```
这些改变可以使你的代码更加易于维护和理解。